jaffa
jaffa

Reputation: 27370

How to select nodes that don't have a parent node?

I would like to take a string like so:

<div>my div 1</div><p>para1</p><p>para2</p><p>para3</p><div>my div 2</div>

and then remove all <p> nodes.

I'm having difficulty with this because I think that the string above has no context, and JQuery needs a context to work with to allow selectors to work:

var p = "<div>my div 1</div><p>para1</p><p>para2</p><p>para3</p><div>my div 2</div>"
var pj = $(p)

When I run the statement below in FireBug, I get no elements returned. Is this because the 'p' variable needs to be wrapped in another div for it to work? I want to be able to strip the elements from the string, even though it is not part of the DOM.

$("p",pj)

Upvotes: 0

Views: 351

Answers (1)

Nick Craver
Nick Craver

Reputation: 630637

You need .filter() to search elements at the same level, like this:

$(pj).filter("p");

$("p",pj) translates to $(pj).find("p") under the covers, that's why it's not finding anything, because the <p> elements are descendants of pj, they're members. To be clear, jQuery doesn't need them to be contained in anything, it's a descendant vs non-descendant issue.


The alternative approach is to add them to a temporary fragment and always use .find(), like this:

var p = "<div>my div 1</div><p>para1</p><p>para2</p><p>para3</p><div>my div 2</div>"
var pj = $('<div />').html(p);

Then $("p",pj) would work.

Upvotes: 2

Related Questions