How does jQuery treat comment elements?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-23 07:48:01

问题


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?


回答1:


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; 
                                               });



回答2:


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("*"));


来源:https://stackoverflow.com/questions/8229076/how-does-jquery-treat-comment-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!