How to get the first child id inside the div using JQuery
How to get the first child id inside the div using JQuery.
Sample code:
<div id='id1'>
<a id='a1' />
<a id='a2' />
<a id='a3' />
</div>
I wa开发者_高级运维nt to get the id a1
.
I have tried $('#id1 a:first-child').html()
to get the text. How to get the id?
$("#id1:first-child").attr("id")
Use this to get first element of id1 element:
$("#id1").children(":first");
Below Answer Will Select First 'a' Element under element With ID - 'id1" ( As per Asked in Question )
$('#id1 a:first-child').attr('id')
Below Code will only Select First Div with ID - 'id1' So it will select that div not child element of div ( But its not as per asked by question in answer )
$('#id1:first-child').attr('id')
If you want immediate first child you need
$(element).first();
If you want particular first element in the dom from your element then use below
var spanElement = $(elementId).find(".redClass :first");
$(spanElement).addClass("yourClassHere");
try out : http://jsfiddle.net/vgGbc/2/
$('#id1:first-child').attr('id')
$("#form .form-group").first();
May be helpful for someone.
To make things super clear, this is what to do in order to find any element within a certain element you already can access, in this case that is the element with id='e1':
<style>
.c1{ border:2px solid red; padding: 12px; background: lightyellow }
.c2{ border:2px solid green; padding: 12px; background: lightyellow }
.c3{ border:2px solid blue; padding: 12px; background: lightyellow }
</style>
<div class='c1' id='e1'>
<div class='c2' id='e2'>
<div class='c3' id='e3'>text</div>
</div>
</div>
The following line get's you div e2:
var child2 = $('#e1').find(".c2");
The following lines both get you div e3:
var child3 = $('#e1').find(".c3");
var child3_1 = $('#e1').find(".c2 :first");
To change something about these, you have to use the objects like this:
$(child2).css('background-color','white');
$(child3).css('border','4px dotted pink');
$(child3_1).css('color','#ef2323');
I hope this is clear and helpful.
Edit: This comment should be removed because it provides no value.
精彩评论