vabm vabm - 3 months ago 8
HTML Question

Access ID of unknown child DIV with javascript / jquery

I am trying to access the id of an unknown div using its parent id. A simplified version of my html is something like:

<div id="firstId">
<div id="secondId"></div>
</div>


Just to be clear, I don't know the id of the child div. Then, I am trying to use the DOM to access it with:

var idd = $(".firstId").children().attr("id");
alert(idd);


But I get an
undefined
alert (fiddle). Not sure what might be the problem.

Answer

You have provided the Id and accessing it by using class selector, which is wrong. Try this:

var idd = $("#firstId").children().attr("id");
alert(idd);