ReynierPM ReynierPM - 1 month ago 4
Javascript Question

Find the ID of a nested element in jQuery

I have the following HTML code:

<div id="div1">
<div></div>
<div></div>
<div></div>
<div></div>
<div id="iwantthis"> </div>
</div>



  • The ID of the parent DIV will be always the same meaning
    #div1
    won't change

  • The ID of the children DIV
    #iwantthis
    is generated dynamically



I need to get the value of that dynamic ID and I can't use
.find()
method since it's tied to a given selector. I have search for this and a lot of topics comes out but none fit my scenario (or at least I couldn't find it).

What's the best way to find such ID value?


Note: In addition to the post keep this in mind: at the moment I will have 4 DIV before the
current one holding the dynamic ID but this could change at any
moment.

Answer

You can set context of jQuery() to #div1, select child element having attribute [id] or specific id

var div = $(" [id]", document.getElementById("div1"));
var id = div.attr("id");