Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 768
tillda Avatar asked Nov 22 '11 15:11

tillda


People also ask

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.

Which methods return the element as a jQuery object?

The jQuery selector finds particular DOM element(s) and wraps them with jQuery object. For example, document. getElementById() in the JavaScript will return DOM object whereas $('#id') will return jQuery object.

What does $() short and stand for in jQuery?

$ is a short form of jQuery function. $() = jQuery() = window. $() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements.

How HTML elements are used in jQuery with example?

The html() method in jQuery is used to get the contents of the first element in the set of matched elements or is used to set the HTML contents of every matched element. It returns the content of the first matched element. This function does not accept any arguments.


1 Answers

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; 
                                               });
like image 112
RightSaidFred Avatar answered Oct 08 '22 14:10

RightSaidFred