Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery getting element index despite wrapper / parent element?

I have divs with same class, but each 3 are wrapped in a parent div. I can't get the index the way I want it. I am sorry, could anyone help me to get the index as number from 0 to 8.. when i click on any element? despite the parent element.

Here is my full code for your testing.

<div class="more-content">
    <div class="post">post 1</div>
    <div class="post">post 2</div>
    <div class="post">post 3</div>
</div>
<div class="more-content">
    <div class="post">post 4</div>
    <div class="post">post 5</div>
    <div class="post">post 6</div>
</div>
<div class="more-content">
    <div class="post">post 7</div>
    <div class="post">post 8</div>
    <div class="post">post 9</div>
</div>

<script type="text/javascript">
$(function() {

    // navigate posts with next/prev buttons
    $(".post").click(function(){
        alert($(this).index());
    });

});
</script>

If i click i get index 0, 1, 2 ..i think because each 3 items are wrapped in parent? I am new with jquery, any help appreciated. what i need is get the index of post with same class.. say post 6 = index 5.. and so on

UPDATE How can I get the same result if the clicked element is a child anchor in the post div and not the post div directly?

like image 328
Ahmed Fouad Avatar asked Mar 14 '26 16:03

Ahmed Fouad


1 Answers

Try index method with this as an argument:

$(".post").click(function() {
    alert($(".post").index(this));
});​

DEMO: http://jsfiddle.net/Nryf3/

like image 85
VisioN Avatar answered Mar 17 '26 04:03

VisioN