Reputation: 2627
Is it possible to select an element by id, that is already existing inside a created DOM element?
For example:
var domElement = $('#id1');
domElement.find('#id2').value = '';
Upvotes: 2
Views: 346
Reputation: 44125
Yes, it's completely possible - and it even works with nested elements:
$("#button").on("click", () => {
var domElement = $("#id1");
domElement.find("#id2").value = "Different text!";
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="id1">
<div>
<section>
<input id="id2" type="text" value="Text">
</section>
</div>
</div>
<button id="button">Click me!</button>
As @freefaller pointed out in the comments, using value
with a jQuery object may not work on some browsers (I think it only works on Safari), so use val
instead:
$("#button").on("click", () => {
var domElement = $("#id1");
domElement.find("#id2").val("Different text!");
});
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="id1">
<div>
<section>
<input id="id2" type="text" value="Text">
</section>
</div>
</div>
<button id="button">Click me!</button>
Upvotes: 2