jQuery what is the difference between $('

') and $('p')

后端 未结 3 645
野的像风
野的像风 2021-01-23 09:46

Can someone explain to me the difference between $(\'

\') and $(\'p\') in jQuery.

for example, if i write:

$(\'body\').         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-23 10:17

    The difference:

    $('

    ') creates a new paragraph-element

    $('p') select all paragraph-elements in the DOM

    Your cases:

    Example 1:

    $('body').append($('

    ').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

    elements, so nothing matches the $("p") selector.

提交回复
热议问题