jQuery 1.4 added a shorthand way for constructing new DOM Elements and filling in some of their attributes:
jQuery( html, props )
html: A string defining a single, standalone, HTML element (e.g. or ).
props: A map of attributes, events, and methods to call on the newly-created element.
But, I just noticed this strangeness (with jQuery 1.5.1):
>>> $("<img />", { height: 4 })[0].height
0
>>> $("<img />").attr({ height: 4 })[0].height
4
So, they are some differences between the shorthand and the longer way..! Is this a bug or is it intentional? Are there any other ones with similar behaviour which I should watch out for?
From the docs:
So basically the snippet is not equivalent to
$("<img />").attr({ height: 4 })but to$("<img />").height(4)and the html it evaluates to is<img style="height: 4px" />– hence the returned0.