Error in jQuery DOM element builder for images with width / height?

jQuery 1.4 docs describe how jQuery can be used to create DOM elements on the fly from the provided HTML string and set of attributes. For example:

var d = $('<div/>', {id:'foo', className:'bar'}); d; // => [<div id="foo" class="bar"></div>] d.attr('id'); // => "foo" d.attr('class'); // => "bar" 

It's great; however, an error occurs when using this shortcut for images with width and height. Instead of setting attributes (as implied by the attr () function, it sets the CSS style:

 var x = $('<img/>', {width:10, height:20}); x; // => [<img style=​"width:​ 10px;​ height:​ 20px;​ ">​]!!! x.attr('width'); // => 0!!! x.attr('height'); // => 0!!! 

This is even more confusing since jQuery behaves as expected when a new image from the constructor is given:

 var y = $(new Image(10, 20)); y; // => [<img width=​"10" height=​"20">] y.attr('width'); // => 10 y.attr('height'); // => 20 

Is this just a bug in jQuery 1.4.2 or the expected behavior for some reason?

+3
jquery
May 17 '11 at 21:15
source share
1 answer

Quoting jQuery Method

As with jQuery 1.4 , the second argument can take a map consisting of superset properties that can be passed in the .attr() way. In addition, any type of event can be transmitted, and the following jQuery methods can be called: val, css, html, text, data, width , height, or offset.

So, these properties are processed by the appropriate methods, and .width() and .height() apply their values ​​in the style attribute.




Follow the steps from the comments below:

At least this is a documentation error in which jQuery does not recognize a conflict between the legal properties of height and width and jQuery methods of the same name.

More appropriately, this is an API error that needs to be resolved. An error report was sent here.

Note that this only affects the optional props argument when creating items. The .attr() method works correctly with respect to width and height .




Update: jQuery has confirmed the conflict, but will not provide any fixes allowing its users to apply width and height in the props argument when creating elements.

Therefore, these properties are not supported for assignment in this way. You will need to apply these properties separately from the others in a separate call to the .attr() function, which supports them correctly.

 var x = $('<img/>', { src:'some/path/to.jpg', alt:'some text' }).attr({ width:100, height:100 }); 
+2
May 17 '11 at 21:34
source share



All Articles