get the nth-child number of an element in jquery

前端 未结 3 1934
天命终不由人
天命终不由人 2021-02-03 20:23

I have a class of multiple \'DIV\' elements and inside it are list of \'p\' elements. See below:

This is content 1&l

3条回答
  •  -上瘾入骨i
    2021-02-03 21:14

    $('.container').children('p').hover(function(){
        //get the nth child of p from parent class 'container'
        var n = 1;
        var child = $(this).parent().find("p:eq("+n+")");
    });
    

    Should work!

    Or if you want to know the index of the hovered element:

    $('.container').children('p').each(function(index,element) {
        // use closure to retain index
        $(element).hover(function(index){
            return function() { alert(index); }
        }(index);
    }
    

    See http://api.jquery.com/each/

提交回复
热议问题