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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With