tillda
tillda

Reputation: 18680

How does jQuery treat comment elements?

I always thought that jQuery operates only on DOM elements, that is those nodes that have nodeType == 1.

However I'm shocked that while creating HTML $("<p> </p><!-- comment -->") results in:

[p, Comment { data=" comment ", length=21, nodeName="#comment", more...}] (Firebug formatting)

I accepted some HTML by AJAX and a DOM Comment was created this way and passed somewhere to a function that is applicable only to elements: defaultView.getComputedStyle( elem, null )

Is there some clean way out of this?

Upvotes: 8

Views: 1308

Answers (2)

RightSaidFred
RightSaidFred

Reputation: 11327

I always thought that jQuery operates only on DOM elements

Its selectors only select DOM elements. In your case, you're creating nodes from the HTML string you've provided. So jQuery parses the string and gives you back the nodes you're asking for.

To clean it, do a .filter().

var els = $("<p> </p><!-- comment -->").filter(function() { 
                                                  return this.nodeType === 1; 
                                               });

Upvotes: 5

Alex Turpin
Alex Turpin

Reputation: 47776

Hmm, an interesting problem. After fiddling for a bit I found out that you can remove them using .filter with the universal selector (*).

var a = $("<p></p><!-- comment -->");
console.log(a);
console.log(a.filter("*"));

Upvotes: 5

Related Questions