Navigate a rootless dom with JQuery

后端 未结 4 1969
借酒劲吻你
借酒劲吻你 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 = $('
    ').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.

提交回复
热议问题