Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the id of the first div within the clicked li

<li class="intro-item">
    <a href="...">Something</a>
        <div id="bar1"></div>
        <div id="bar2"></div>
        <div id="bar3"></div>
        <div id="bar4"></div>
        <div id="bar5"></div>
</li>

I want to get the id of the first div (it's bar1 here) when li is clicked. And there are more lis same as above. All those lis also have the CSS class "intro-item" When I click each of these, I want to get the id of first div.

The idea is like this

$('li.intro-item').click(function(){
    alert($('(this) div:first').attr('id'));// here I can't apply this keyword that's the problem.
    });
like image 613
Prasad Lakmal Avatar asked Jun 16 '15 08:06

Prasad Lakmal


People also ask

How do I get the ID of a clicked element?

One of the ways to get an ID attribute of a clicked element is that you actually attach click events to all the buttons inside For loop. Get DOM references to all the buttons by invoking getElementsByTagName() on the document object with an argument button.

How do I find div id?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.


1 Answers

Pass this as a context to jQuery

$('li.intro-item').click(function () {
    alert($('div:first', this).attr('id')); //or $(this).find('div:first')
});
like image 82
Arun P Johny Avatar answered Sep 30 '22 04:09

Arun P Johny