Hi,

I have a HTML structure like this:

<div>
    <div id="a"></div>
    <div id="b"></div>
    <div id="c"></div>
</div>

I know the ID of an element (let's say it's #b), and i need to know which index it has in the parent div. In this case that would be 2. How do i get that number using javascript/jQuery?

Recommended Answers

All 4 Replies

how about this:

    <div>
        <div id="a" onclick="getIndex(this);"></div>
        <div id="b" onclick="getIndex(this);"></div>
        <div id="c" onclick="getIndex(this);"></div>
    </div>

    function getIndex(elem) {
    var $t = $(elem);
    alert($t.parent().index());
}

Note that index() is zero-based, so you may want to add 1

That returns the element with id 'b', not it's index in the list.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.