javascript - get the id of the first div within the clicked li - Stack Overflow

<li class="intro-item"><a href="...">Something<a><div id=&quo

<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.
    });
<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.
    });
Share Improve this question edited Jun 16, 2015 at 8:15 Prasad Lakmal asked Jun 16, 2015 at 8:13 Prasad LakmalPrasad Lakmal 1491 silver badge9 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

Pass this as a context to jQuery

$('li.intro-item').click(function () {
    alert($('div:first', this).attr('id')); //or $(this).find('div:first')
});

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'));
});

Fiddle

$('li.quiz-intro-item').click(function(){
   alert($(this).find("div:first").attr("id"));
});

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742283988a4414996.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信