Given the following html:
<div class="my-container">
<div class="x">
<a href="#">Link 1</a>
</div>
<div class="x">
<a href="#">Link 2</a>
</div>
<div class="x">
<a href="#">Link 3</a>
</div>
<div class="x y">
<a href="#">Link 4</a>
</div>
<div class="x">
<a href="#">Link 5</a>
</div>
<div class="x y">
<a href="#">Link 6</a>
</div>
<div class="x">
<a href="#">Link 7</a>
</div>
</div>
Which elements get the y
class - is a dynamic thing, which changes during runtime based on different user interactions.
On mouse over an anchor (I can assume that the anchor is in a div with the y
class, because only those are visible), I need to get the index of it's container (that div with the y
class), but restricted to that y
class.
Meaning:
0
(first element with class y
) 1
(second element with class y
) .index()
doesn't help me here
EDIT: @Kevin B I've read the docs, but couldn't make it work. The closest thing I could find there was to pass a collection to .index()
, which I've tried. But didn't work (also, their example for the collection is with vanilla js document.getElementById - that didn't work for me, need to work with classes; tried to adapt: myCollection = $(this).closest('.my-container').children('.y') and passed that to .index()
, and it didn't work). I wouldn't post without google-ing first and also going through the docs, don't know why the down vote (not pointing any fingers, I'm not assuming I know who's is it). Just because I said ".index()" doesn't help me"? Well, I've tried whatever I understood I could do with it, and couldn't make it happen. That's why I posted.
As said in the comments, index is exactly what you need:
$(document).ready(function() {
//mousein
$("a").hover(function(){
var parent = $('.my-container').eq(2); // the 3rd "my-container"
console.log(parent.find('.y a').index(this)); //-1 if elm doesnt exist
},
//mouseout
function(){
})
});
As said in the comments, index is exactly what you need:
$(document).ready(function() {
//mousein
$("a").hover(function(){
console.log($(this).index('.y a')); //-1 if elm doesnt exist
},
//mouseout
function(){
})
});
var count = 1; $(".my-container div").on('mouseover',function(){ if ($(this).attr("class").indexOf('y') > -1){ alert(count + "th mouseover on y class"); count++; } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="my-container"> <div class="x"> <a href="#">Link 1</a> </div> <div class="x"> <a href="#">Link 2</a> </div> <div class="x"> <a href="#">Link 3</a> </div> <div class="xy"> <a href="#">Link 4</a> </div> <div class="x"> <a href="#">Link 5</a> </div> <div class="xy"> <a href="#">Link 6</a> </div> <div class="x"> <a href="#">Link 7</a> </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.