Reputation: 18660
I have the following HTML code:
<div id="div1">
<div></div>
<div></div>
<div></div>
<div></div>
<div id="iwantthis"> </div>
</div>
#div1
won't change#iwantthis
is generated dynamicallyI 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
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
Reputation: 7662
If you know how many div
s 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
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