so let's say I have some jQuery that runs as follows:
var myVar1 = $('.myClass1, .myClass2');
myFunction(myVar1); // Does something to element myVar1
var myVar2 = $('#myId').parent();
myFunction(myVar2); // Does something to element myVar2
Here's the problem. Sometimes #myId's parent will be its own element, but it will sometimes also have either class .myClass1 or .myClass2. However, I don't want to run myFunction() on #myId's parent twice.
So the html could either be like:
<div class="myClass1"></div>
<div class="myClass1"></div>
<div class="myClass2"></div>
<div>
<div id="myId"></div>
</div>
Or it could be like this:
<div class="myClass1">
<div id="myId"></div>
</div>
<div class="myClass1"></div>
<div class="myClass2"></div>
The jQuery needs to call the function on each <div> only once.
How do I detect if myVar2 is contained within myVar1?
To quote you,
How do I detect if myVar2 is contained within myVar1?
Each of your variables is returning a jQuery object, which is great, sure. If you want to find out if one jQuery object contains yet another jQuery object in its returned set, you can use jQuery's index() method.
From index():
If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.
So we know we can reasonably get a number equal to or greater than zero representing the index of this other jQuery object IF it exists inside of myVar1, otherwise we get -1 if it doesn't exist.
if var myVar2 = $('#myId').parent(); is included in var myVar1 = $('.myClass1, .myClass2'), then running myVar1.index(myVar2) will return a number greater than or equal to zero. Otherwise -1.
Hope that helps!
You can do this using the jQuery not selector, which removes matched elements from the set. To modify your example:
var one = $('.myClass1, .myClass2');
myFunction(one); // Does something to element myVar1
var two = $('#myId').not(one).parent();
myFunction(two); // Does something to element myVar2
This modification to the second selection will make it so that #myId is selected only if the element does not have either the .myClass1 or .myClass2 class attached.
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