How does jQuery treat comment elements?

2019-06-16 15:19发布

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?

2条回答
Emotional °昔
2楼-- · 2019-06-16 15:42

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("*"));
查看更多
一纸荒年 Trace。
3楼-- · 2019-06-16 15:59

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; 
                                               });
查看更多
登录 后发表回答