<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.
});
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.
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.
Pass this
as a context to jQuery
$('li.intro-item').click(function () {
alert($('div:first', this).attr('id')); //or $(this).find('div:first')
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With