0

I am new to jQuery and i have a problem about getting the value that i need from a variable. More specific I have this list on html file.

<ul id="menu">
<li class="mainmenu" id="newsarticles"><a href="#">News &amp; articles</a>

    <ul id="newsarticles">
        <li class="submenu" id="news"> <a href="#">News</a>

        </li>
        <li class="submenu" id="articles"> <a href="#">Articles</a>

        </li>
    </ul>
    <li class="mainmenu" id="contactus"><a href="#">Contact Us</a>
    </li>
</ul>

Now i want to use the same function both to mainmenu and submenu.

$("#menu li").click(Menu_function);

My problem is that when i click on submenu, variable $(this) has two values. one for the li inside the submenu and one for the li of mainmenu.

now i would like to do something like this in my function:

var currentId = $(this).attr('id');

How could I get only one value?

Any help appreciated.

JMast
  • 15
  • 4

3 Answers3

1

You'll want

$('#menu').click(function(evt) {
  var currentId = $(evt.target).closest('li').attr('id');
});
bmavity
  • 2,477
  • 2
  • 24
  • 23
1

You can add the click function to both items using an "each" selector:

$('#menu li').each( function(index) {
    $(this).click( function() {
      var id = $(this).attr('id');

      // do whatever you need to here
    });
});
dcp
  • 54,410
  • 22
  • 144
  • 164
0

You may use each method of jquery to traverse all of them and add onclick on them. something similar what dcp has mentioned in his answer:

$('#menu li').each( function() {
    // add click method on this element ($(this))
    $(this).click( function() {
    });
});
Amar
  • 11,930
  • 5
  • 50
  • 73