Given this html string:
var string = "<div></div><p></p>";
I create a jQuery object with it:
var dom = $(string);
Is there any chance to use selectors to point to one of its tag? Without embed it all in a newly created one, of course.
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!');
.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"));
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).
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
find() or both.
©2020 All rights reserved.