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)
You need
.filter()to search elements at the same level, like this:$("p",pj)translates to$(pj).find("p")under the covers, that’s why it’s not finding anything, because the<p>elements are descendants ofpj, 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:Then
$("p",pj)would work.