Navigate a rootless dom with JQuery

后端 未结 4 1968
借酒劲吻你
借酒劲吻你 2021-01-21 07:04

Given this html string:

var string = \"

\";

I create a jQuery object with it:

var dom          


        
相关标签:
4条回答
  • 2021-01-21 07:27

    A simpler method to work with an HTML snippet that may contain anything is to use a temporary parent node, then use/extract its children.

    var $root = $('<div></div>').append(yourHtml);
    $root.find('p').addClass('foo');// or whatever
    $('.bar').append($root.contents());// put filtered content in your DOM; or
    var filteredHtml = $root.html();// get it back to a string of markup
    

    Now the code is less coupled to the contents and more flexible because you don't have to know ahead of time whether you'd need to use filter(), find() or both.

    0 讨论(0)
  • 2021-01-21 07:35

    .find looks inside of the element. In your case though you're creating a div and a paragraph next to one another. Move the paragraph inside the div and your code will work.

    Or you can wrap both of those elements into a third, parent.

    var string = "<div><p></p></div>";
    
    var dom = $(string);
    
    console.log(dom.find("p"));
    
    0 讨论(0)
  • 2021-01-21 07:44

    When there's no root element you'll need to use filter() to get top level elements:

    var string = "<div></div><p></p>";
    var $dom = $(string).appendTo('body'); // appendTo() is only for purposes of this demo
    $dom.filter("p").text('hello world!');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    0 讨论(0)
  • 2021-01-21 07:51
    var html = "<div></div><p></p>";
    var parser = new DOMParser();
    var dom = $(parser.parseFromString(html, "text/html"));
    
    //work with dom
    dom.find("p");
    

    the parser will create an html document (not appended to your document).

    0 讨论(0)
提交回复
热议问题