Can I use jQuery selectors on an HTML string that is not attached to the DOM?

后端 未结 3 1564
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 04:48

So if I have a variable like

var ht = \"

Paragraph Here

\"

If it was attached to the DOM I could

3条回答
  •  天涯浪人
    2020-12-15 05:12

    There is no mystery. Selecting

    $('p')  
    

    selects p elements of the document, the implied context.

    But the p elements in:

    var ht = "

    Paragraph Here

    ";

    are not attached to the document (DOM) so it's OK if they are not selected.

    Fortunately the $() function has a second argument, the context, that has to be used here, like:

    $('p', $(ht).context) 
    

提交回复
热议问题