ReynierPM
ReynierPM

Reputation: 18660

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>

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.

Upvotes: 1

Views: 455

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388316

You can use the child selector relationship with attribute selector

var $target = $('#div1 > div[id]'); //use the id attribute to select the target element
$target.addClass('selected');

//since the target is the last child you can use that relationship also

$('#div1 > div').last().html('Using last child');
.selected {
  background-color: lightgreen;
}
#div1 div {
  border: 1px solid grey;
  padding: 5px;
  margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div id="iwantthis"></div>
</div>

Upvotes: 0

Niyoko
Niyoko

Reputation: 7662

If you know how many divs before the item, then you can use following selector.

var selector = "#div1>";

// loop 4 times, replace with how many div's before "wanted" div
// of course it can be a variable
for(var i = 0; i<4; i++) { 
    selector += "div+";
}

selector += "div";
console.log($(selector).attr("id"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div id="iwantthis"> </div>
</div>

Upvotes: 0

guest271314
guest271314

Reputation: 1

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

Upvotes: 3

Related Questions