Gabriel Santos
Gabriel Santos

Reputation: 4974

Get index of different element

I want to get the index of an div with id of clicked anchor:

<ul>
    <li><a href="#div1">Div 1</a></li>
    <li><a href="#div2">Div 2</a></li>
    <li><a href="#div3">Div 3</a></li>
</ul>
<div class="foo">
    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
</div>

So, if I click Div 1 I want to get .foo #div1 index, but I can't do this by myself.

I have tried:

$('ul li a').click(function() {
    var target = $(this).attr('href');

    // $(target).index();
    // $('.foo').index(target);
})

Thanks =)

Upvotes: 2

Views: 112

Answers (3)

jfriend00
jfriend00

Reputation: 707258

You can get the corresponding div in .foo with the same index as the one clicked on with this:

$('ul a').click(function() {
    // get the index of the item that was clicked
    var index = $(this).closest("li").index();
    // find that same index in .foo
    var target = $(".foo > div").eq(index);
})

Or, if you want to use the href, you can do it like this:

$('ul a').click(function() {
    // use getAttribute so we don't get a fully qualified URL
    var target = $(this.getAttribute("href"));
})

Or, another way to do it using a fully qualified URL:

$('ul a').click(function() {
    var target = $(this.href.replace(/^.*#/, "#"));
})

Upvotes: 4

tptcat
tptcat

Reputation: 3961

Cleaned up a bit:

$(function() {
    $('li a').on('click', function() {
        var target = $(this).attr('href');
        $('.foo ' + target).html('hello');
    });
});

I put the event handlers directly on the a inside the li. I've also used jQuery's on() method introduced in 1.7 which is the preferred way for event handlers.

then:

<ul>
    <li><a href="#div1">Div 1</a></li>
    <li><a href="#div2">Div 2</a></li>
    <li><a href="#div3">Div 3</a></li>
</ul>
<div class="foo">
    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
</div>

To get the index of the clicked item:

$('.foo ' + target).index();

jsFiddle example: http://jsfiddle.net/DNfYg/

Upvotes: 0

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

You specified the ID attributes incorrectly.

Lose the hash symbol from the id attributes, but not from href ones. Then your second attempt will work.

Upvotes: 0

Related Questions