简体   繁体   中英

Get id of div in nested HTML elements using jquery

How can I get, using jquery, the id of the first div with class: post (367), in the following HTML code:

<div id="own-posts">
  <span class="title">Me</span>    
  <div class="posts_container">
    <div class="post"></div>  

    <div id="367" class="post"></div>
    <div id="365" class="post"></div>
    <div id="345" class="post"></div>
    <div id="343" class="post"></div>

  </div>

</div>

Among the solutions I tried:

$('#own-posts').children()[1].children()[1].attr('id');

The first .post element doesn't have an ID, so I guess you mean the first .post element that actually has an ID attribute :

var id = $('#own-posts .post[id]:first').prop('id');

FIDDLE

$('#own-posts .post:first').prop('id'); works if all divs with that class have a id.

Otherwise if the pattern is the first div.post does not have id, but the second does you can use:

$('#own-posts .post').eq(1).prop('id');

I used .prop() because of this

Try

$('#own-posts .post').eq(1).prop('id');

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM