RGO
RGO

Reputation: 4727

How to obtain id of the surronding list item in jQuery?

I am trying to use jQuery tabs but there is an issue that I can't resolve.

Somewhere inside the document's body, I have:

<ul class="tabs-horizontal">
    <li id="a" class="current"><a href="#">Tab A</a></li>
    <li id="b"><a href="#">Tab B</a></li>
</ul>

In my script section, I have:

<script type="text/javascript">

    $(document).ready(function(){

        var activeTabIndex = -1;
        var tabNames = ["a","b"];

        $(".tabs-horizontal > li").click(function(e){
            for(var i=0;i<tabNames.length;i++) {
                if(e.target.id == tabNames[i]) {
                    activeTabIndex = i;
                } else {
                    $("#"+tabNames[i]).removeClass("current");
                }
            }
            $("#"+tabNames[activeTabIndex]).addClass("current");
            return false;
        });
    });

</script>

It doesn't work because I'm comparing e.target.id with tabNames elements. When I debugged, I found e.target.id returns -1.

So, how can I obtain those two li IDs (i.e. "a" and "b")?

Thanks.

Upvotes: 0

Views: 72

Answers (4)

codetantrik
codetantrik

Reputation: 315

e.target points to the a link inside the li. you should use e.target.parentElement.id

Upvotes: 1

palaѕн
palaѕн

Reputation: 73896

You can do this:

$(".tabs-horizontal > li").click(function () {
    $('li.current').removeClass("current");
    $(this).addClass("current");
    return false;
});

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074178

Inside a jQuery event handler, this will be the DOM element on which you hooked the event. Since you're hooking the event on the li elements, this.id will be their ID.

But you don't need the ID. You can just use traversal to do what you're trying to do. I was about to show how, but undefined already has.

Upvotes: 4

Ram
Ram

Reputation: 144679

$(".tabs-horizontal > li").click(function(e) {
      $(this).addClass("current").siblings().removeClass("current");
      return false;
});

Upvotes: 6

Related Questions