Reputation: 75
I am trying to understand what does this code do and why have we used addBack() with find() when the same results are obtained without using addBack()
Take these two examples
$("body div").find("*").addBack().contents().filter(function(){
return this.nodeType === 3 && /shaolin/i.test(this.nodeValue);
})
vs
$("#myDiv").find("*").addBack().contents().filter(function(){
return this.nodeType === 3 && /judo/i.test(this.nodeValue);
})
Also why are we doing /shaolin/i.test(this.nodeValue);?
Upvotes: 3
Views: 453
Reputation: 781716
find()
only returns the descendants that match the selector. The code uses addBack
so that it will also search the contents of the original body div
elements, in addition to all their descendants.
If none of the top-level DIV
elements match the filter function, then the result will be the same with or without the addBack
. The code is trying to be thorough, so it won't miss anything.
The code is looking for all text nodes within body div
that contain the word shaolin
. /shaolin
is a regular expression, and it tests each text node's value against this.
Upvotes: 5
Reputation: 38112
From the docs:
.addBack() add the previous set of elements on the stack to the current set, optionally filtered by a selector.
In your case, the addBack()
add any div
inside your body
to the current set which is any element that are the children of any div
.
So it's not only find the contents of an element placed under a div
but also the div
contents itself.
Upvotes: 1