Navigate a rootless dom with JQuery

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.

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=""></script>


.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);

var html = "<div></div><p></p>";
var parser = new DOMParser();
var dom = $(parser.parseFromString(html, "text/html"));

//work with dom

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 filter(), find() or both.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.