0

Fairly new to jquery. good stuff btw. however. There's something I can't seem to understand. I've got a list that I use as a navbar. Each list item was given an id.

I want to get that ID with jQuery.

the way the items are defined:

<ul id="mainList">
<li id="liFirstItem"><a class="main-link" href="#">First One</a>
    <ul class="sub-links">            
        <li><a href="#">Sub Item 1</a></li>
        <li><a href="#">Sub Item 2</a></li>
    </ul>
</li>
</ul>

comming from here; Getting the ID of the element that fired an event

these are my attempts;

    /*testing*/                        
    var current = "Item: " + this.text + "\n";
    /*current += "Id: " + this.id;*/
    /*current += "Id: " + event.target.id;*/

    var target = event.target || event.srcElement;
    var id = target.id

    current += "Id: " + id;

    alert(current.toString());

the item always provides the correct text of the item clicked, e.g. "First One". However, the ID of this is always empty. Any ideas, what am I missing here?

Thanks a lot!

Community
  • 1
  • 1
Obelix
  • 708
  • 11
  • 24
  • 3
    There is no `id` attribute for the `a` elements? what is the expected output – Arun P Johny May 07 '13 at 13:28
  • Are you wiring up the click events on the anchor or the listitem element? What about the sub links, what id should they display when clicked? – Terence May 07 '13 at 15:14
  • Arun that was the solution! Missed that completely #shameonme. I was trying to select the li item, but of course, the eventsource is the hyperlink and not the list item. pfff... – Obelix May 07 '13 at 16:58

1 Answers1

2

Although you don't appear to have ID's set for your elements, this is how you would go about it. Attach a click event handler to all of the links in the sub-list ul. Then alert the ID of the link that was clicked.

$('.sub-links li a').click(function(){
    alert($(this).attr('id'));
});
pmandell
  • 4,288
  • 17
  • 21
  • in the first list item
  • , the id is set to liFirstItem. That's the one i'm after. that one is actually clickable via the "First One". I tried your approach also. but the ID stays the same; empty.
  • – Obelix May 07 '13 at 16:17