text

"); creates such a jQuery collection $( [t...">

Removing comments and text nodes from the jQuery collection

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

creates such a jQuery collection

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

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

And, for extra points,

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

creates such a jQuery collection

 $( p ) 

Is there a safe way to access p, and only p that works, is there a comment or not?

+4
source share
4 answers

The easiest way is filter and a universal selector * , which matches all elements.

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

jsFiddle .

+1
source

Try the demo . It may not be exactly how you intend to use it, but you understand.

 <div class="text"> <!-- comment --> <p>text</p> </div> var html = $('.text').html(); html = $.trim(html.replace(/<!--(.*?)-->/ig, '')); alert(html); 
0
source

One way is to get by index, as in $html = $("<!-- comment --> <p>text</p>"); , you can get the 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]; } 
0
source

All Articles