What is a jQuery angle bracket selector like $ ('<img />')?
Sometimes I see constructs like $('<img/>') . How is $('<img/>') different from $('img') and where can I find out more about it?
I tried looking at jQuery Selectors but found nothing in this format.
The jQuery function is overloaded to create new jQuery elements when passing a string that is similar to HTML. From docs :
If the string is passed as a parameter to $ (), jQuery checks the string to see if it looks like HTML (i.e. starts with
<tag ... >). If not, the string is interpreted as an expression of choice, as explained above. But if the string appears to be a piece of HTML, jQuery tries to create new DOM elements, as described in HTML. Then a jQuery object is created and returned that references these elements.
$('<img/>') creates an image, and $('img') selects all currently existing images.
$('<img />') creates a new <img /> element to insert into the DOM.
$('img') selects all existing <img /> elements.
Typically, you can use $('<img />') to create elements in the DOM as follows:
var toAppend = $('<img />'); toAppend.appendTo($('#myDiv')); If you can use the $('img'); selector $('img'); for CSS processing (as an arbitrary example):
$('img').css('marginTop', 20); The above will add a 20px margin to the top of each image in the DOM.