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

后端 未结 3 1478
爱一瞬间的悲伤
爱一瞬间的悲伤 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:01

    The jQuery object will take HTML and make it in to a DOM structure for further query, you can pass it in directly to create the object, or use it as a context if you just wish to query it.

    Edit: For some reason it seems necessary to wrap it in a DIV, if not already within one in this example. See the jQuery object documentation on this method for further information.

    See test framework for system at: http://jsfiddle.net/hUMqU/

    var ht = "<body><p>Paragraph Here</p></body>";
    $('<div>' + ht + '</div>').find('p').text();
    

    or as context:

    var ht = "<body><p>Paragraph Here</p></body>";
    $('p', '<div>' + ht + '</div>').text();
    
    0 讨论(0)
  • 2020-12-15 05:05

    Just wrap your HTML String into a jQuery object, and then you can run your jQuery selectors from there:

    var htmlString = "<body><p>Paragraph Here</p></body>";
    var elements = $(htmlString);
    
    var p = elements.filter('p').text();
    console.log(p);
    //=> Paragraph Here
    

    Working demo here.

    0 讨论(0)
  • 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 = "<body><p>Paragraph Here</p></body>";  
    

    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) 
    
    0 讨论(0)
提交回复
热议问题