Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing comments and text nodes from jQuery collection

$html = $("<!-- comment --> <p>text</p>");

creates a jQuery collection like so

$( [the comment], [text node], p )

How can I access the paragraph only? .find("p") returns an empty collection

And, for extra points,

$html = $("<p>text</p>");

creates a jQuery collection like so

$( p )

Is there a fail safe way to get at the p, and only the p, that works whether the comment is there or not?

like image 270
wheresrhys Avatar asked Feb 22 '23 15:02

wheresrhys


2 Answers

The simplest way is with filter and the universal selector *, which matches all elements.

$html = $("<!-- comment --> <p>text</p>").filter('*');
like image 121
lonesomeday Avatar answered Feb 25 '23 06:02

lonesomeday


var p = $html.filter(function() { return this.nodeType === 1; });

jsFiddle.

like image 25
alex Avatar answered Feb 25 '23 06:02

alex