Given this html string:
var string = \"\";
I create a jQuery object with it:
var dom
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.
.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"));
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>
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).