user1141649 user1141649 - 1 year ago 62
jQuery Question

How to find jquery element in jquery results?


My terminology may be imperfect so here I try to explain what I mean by "results" or "elements" and I use these words as synonyms.

$("iframe") returns object which contains results like

[0] JQuery object ... (iframe #0)
[1] JQuery object ... (iframe #1)

In this code I am trying to work with these results (children or elements). I am not speaking about nested elements of iframe, but about the iframes only.


I have created some function to filter results of $("iframe"). I need to create function to "invert" the results. So I will work with the results of $("iframe") which are not found by the function

My problem is that I don't know How to identify each result or iframe element in the Variable
? I know that
iframe in iframes
is wrong - I cannot use
because it searches for
key in array
or object. But I need to find exact element in the variable iframes...

var jif = $("iframe");
var iframes = jif.filter(myfunction);
function( k, iframe, iframes) {
if ( !(iframe in iframes) )

so instead of the part:
if ( !(iframe in iframes) )
I need to get:
if jquery element is not in the jquery iframes collection object.

Sorry but I don't know how to explain it better

Answer Source

If you want to check if a specific element is inside some jquery collection you can use the index method:

divs = $('div')
divsA = $('div.a')
divsB = $('div.b')

a = $('#a')
b = $('#b')
c = $('#c')
console.log("check if #a, #b, #c in divs")
console.log(divs.index(a) >= 0)
console.log(divs.index(b) >= 0)
console.log(divs.index(c) >= 0)

console.log("check if #a, #b, #c in divsA")
console.log(divsA.index(a) >= 0)
console.log(divsA.index(b) >= 0)
console.log(divsA.index(c) >= 0)

console.log("check if #a, #b, #c in divsB")
console.log(divsB.index(a) >= 0)
console.log(divsB.index(b) >= 0)
console.log(divsB.index(c) >= 0)
<script src=""></script>
<div id="a" class="a">Div with class a</div>
<div id="b" class="b">Div with class b</div>
<div id="c" class="a b">Div with class a and b</div>

jQuery's index function will work also for elements which are not jquery, but also a regular dom elements:

divsA = $('div.a')

a = document.getElementById('a')
b = document.getElementById('b')
console.log("check if #a, #b divsA")
console.log(divsA.index(a) >= 0)
console.log(divsA.index(b) >= 1)
<script src=""></script>
<div id="a" class="a">Div with class a</div>
<div id="b" class="b">Div with class a</div>