') and $('p')
Can someone explain to me the difference between \')$(\'
and $(\'p\')
in jQuery.
for example, if i write:
$(\'body\').
jQuery can parse HTML an create an actual DOM element. That is, when you do something like $("<p />")
, jQuery is parsing the markup and internally creating a DOM paragraph element that can be appended to the document.
In the other hand, jQuery integrates Sizzle, a CSS selector engine. The jQuery function accepts CSS selectors, meaning that $("p")
is selecting all paragraph elements in the document. You can also use more complex selectors like $("p:first-child")
and select the first paragraph of the document.
Learn more about jQuery CSS selectors here.
$('<p>')
creates a new paragraph (<p>
) element. (<p></p>
)
$('p')
selects all existing paragraph elements.
For example:
$('p').after($('<p>').html('foo'))
Will select all paragraphs and add new paragraphs after them.
The difference:
$('<p>')
creates a new paragraph-element
$('p')
select all paragraph-elements in the DOM
Your cases:
Example 1:
$('body').append($('<p>').html('hello my friend'));
Will create a new paragraph-element, give it some text, and the element will then be added to the body.
Example 2:
$('body').append($('p').html('hello my friend'));
Will select all paragraph-elements already present in the DOM and change their content to 'hello my friend', it will then append them all to the body, which doesn't make much sense, since they already are in the DOM.
Since nothing gets visible when you run this code, your page likely doesn't contain any <p>
elements, so nothing matches the $("p")
selector.