Removing comments and text nodes from jQuery collection

4.1k Views Asked by At
$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?

4

There are 4 best solutions below

3
On BEST ANSWER

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

$html = $("<!-- comment --> <p>text</p>").filter('*');
1
On
var p = $html.filter(function() { return this.nodeType === 1; });

jsFiddle.

1
On

Try this demo. Maybe this is not exactly how you're gonna use it, but you get the point.

<div class="text">
    <!-- comment -->
    <p>text</p>
</div>

var html = $('.text').html();
html = $.trim(html.replace(/<!--(.*?)-->/ig, ''));
alert(html);
1
On

One way is to get by index like in $html = $("<!-- comment --> <p>text</p>"); you can get p tag using $($html[2]).

OR

$html = $("<!-- comment --> <p>text</p>");
$target = new Object();
for(key in $html){
    if(typeof $html[key] ===  'object' && $html[key].localName === 'p')
        $target = $html[key];
}