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');
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');
Share
Improve this question
edited Apr 28, 2016 at 16:34
madhead
33.6k19 gold badges164 silver badges213 bronze badges
asked Sep 28, 2013 at 11:05
Adib ArouiAdib Aroui
5,0656 gold badges44 silver badges95 bronze badges
6
- 3 It is not valid to have an ID starting with a number (except in HTML5), older browser may plain of problems. – Niet the Dark Absol Commented Sep 28, 2013 at 11:15
- @Kolink Thank you for your important remark, I will take it into consideration in future. What about having number in data-attribute, is it causing the same problem? – Adib Aroui Commented Sep 28, 2013 at 11:17
- @whitelettersandblankspaces No, it's not! Following Kolink's ment, even it's pletly valid to start ID with a number in HTML5, CSS still doesn't like it. So you should follow Kolink's advice – A. Wolff Commented Sep 28, 2013 at 11:22
-
@whitelettersandblankspaces I like to use
data-id
when I'm storing an ID number. In jQuery you can access it with.data("id")
if you want (I don't use jQuery myself, so I just use.getAttribute("data-id")
) – Niet the Dark Absol Commented Sep 28, 2013 at 11:23 - 1 @whitelettersandblankspaces you should prefix IDs if using ID attribute, you shouldn't have to prefix IDs if using data-id attribute – A. Wolff Commented Sep 28, 2013 at 11:31
3 Answers
Reset to default 4The 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