Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bug in jQuery DOM element builder for Images with width/height?

Tags:

jquery

The jQuery 1.4 docs describe how jQuery can be used to create DOM elements on the fly from a 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"

This is great; however, there appears to be a bug when using this shortcut for images with width and height. Instead of setting the 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 given a new image from the constructor:

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 expected behavior for some reason?

like image 307
maerics Avatar asked Nov 18 '25 22:11

maerics


1 Answers

Quoting the jQuery method

As of jQuery 1.4, the second argument can accept a map consisting of a superset of the properties that can be passed to the .attr() method. Furthermore, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset.

So, these properties get handled by their respective methods, and .width() and .height() apply their values in the style attribute.


Followup from comments below:

At the very least it is a documentation bug that jQuery doesn't acknowledge the conflict between the legitimate height and width properties, and the jQuery methods of the same name.

More appropriately it's an API bug that needs to be addressed. A bug report has been filed here.

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


Update: jQuery has acknowledged the conflict but won't provide any fix suitable to allow its users to apply width and height in the props argument when creating elements.

As such, those properties are unsupported for assignment in that manner. You'll need to apply those properties apart from the rest in a separate function call to .attr(), which does correctly support them.

var x = $('<img/>', { src:'some/path/to.jpg',
                      alt:'some text' }).attr({ width:100,
                                                height:100 });
like image 106
Gabriele Petrioli Avatar answered Nov 20 '25 12:11

Gabriele Petrioli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!