Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery's .not() method remove text nodes?

Tags:

jquery

The .not() method takes either a selector or an object with which to filter.

The .contents() method returns a jQuery object containing the children and text nodes of an element.

When a selector is used as the argument for .not() it removes the selected elements but also all the text nodes.

When an object is used as the arguement for .not() it removes the object but not the text nodes.

Example:

<p>This is a <span id="aSpan">paragraph</span> tag</p>

$("p").contents().not("span");
> []

But!

var $sp = $("p span");
$("p").contents().not($sp);
> ["This is a ", " tag"]

also

var sp = document.getElementById("aSpan");
$("p").contents().not(sp);
> ["This is a ", " tag"]

Why are text nodes selected by the "span" selector (or any other selector) but not by an object instance?

like image 616
Andy F Avatar asked Dec 04 '12 14:12

Andy F


People also ask

How do you select text in node?

The textNodes of any element can be selected using jQuery by selecting all the nodes and using the filter() method to check the nodeType property. The required element is first selected using the jQuery selector. The contents() method is used on selected elements.

How to remove a function in jQuery?

jQuery remove() Method The remove() method removes the selected elements, including all text and child nodes. This method also removes data and events of the selected elements. Tip: To remove the elements without removing data and events, use the detach() method instead.


1 Answers

The reason why this happens can be traced back to this particular edit, made 3 years ago. It unifies the .filter() and .not() methods, greatly simplifying both since they're effectively each other's opposites.

Before the above edit, .not() would have called .filter() internally if the selector were anything but a string, so it would have operated on a filtered collection (i.e. .nodeType === 1) starting from this revision made 4 years ago.

This means that - based on your code example - before the edit .not(object) would have returned an empty collection as well, which seems more logical than its current behavior.

Now, both .not(object) and .filter(object) operate on the unfiltered collection, though only the former method will exhibit the behavioral difference.

like image 123
Ja͢ck Avatar answered Oct 07 '22 17:10

Ja͢ck