Reputation: 149
<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.
});
Upvotes: 5
Views: 697
Reputation: 388316
Pass this
as a context to jQuery
$('li.intro-item').click(function () {
alert($('div:first', this).attr('id')); //or $(this).find('div:first')
});
Upvotes: 6
Reputation: 1647
with this :
<li class="intro-item">
<a href="#">Something</a>
<div id="bar1">1</div>
<div id="bar2">2</div>
<div id="bar3">3</div>
<div id="bar4">4</div>
<div id="bar5">5</div>
</li>
<li class="intro-item">
<a href="#">Something</a>
<div id="bar21">21</div>
<div id="bar22">22</div>
<div id="bar23">23</div>
<div id="bar24">24</div>
<div id="bar25">25</div>
</li>
and this snippet of javascript and jQuery :
$("li.intro-item").click(function () {
// this is the 'clicked' DOM Element
// use $(this) to wrap it into a jQuery wrapped set
alert($(this).find("div:first").attr('id'));
});
you have clickable li's that open an alert with the id of the li's first div.
Upvotes: 1
Reputation: 801
$('li.quiz-intro-item').click(function(){
alert($(this).find("div:first").attr("id"));
});
Upvotes: 1
Reputation: 15393
Use $(this)
for getting current li object and .find()
to search the div element and .eq(0)
is used to take first index
$('li.intro-item').click(function(event){
event.preventDefault();
alert($(this).find('div:eq(0)').attr('id'));
});
Upvotes: 5