ReynierPM ReynierPM - 9 months ago 74
Javascript Question

Find the ID of a nested element in jQuery

I have the following HTML code:

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

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

  • The ID of the children DIV
    is generated dynamically

I need to get the value of that dynamic ID and I can't use
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

Answer Source

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");