I have a div created using javascript.
The div has a varying number of child elements that are all check boxes.
I want to retrieve the id's of all the checkboxes using a loop.
The div has been passed through into the class I am using, and has been called:
oInput
I know this is working fine as I am able to retrieve the number of child elements that the div has, using the following line:
oInput.childNodes.length
But my problem is I do not know how to retrieve the id of the child elements. All I want to do is to get the id's to display in an alert box for now.
So far I have:
for (var ii = 0; ii < oInput.childNodes.length; ii++)
{
var childId = oInput.childNodes[ii].id;
alert("Child " + childId);
}
But this is not the correct solution. I have searched around but there does not seem to be a clear answer to this question anywhere. I am only looking for a solution using javascript that will display the answer in the alert box in the loop.
This works for me:
<html>
<body>
<div id="oInput">
<input id="1" type="text">
<input id="2" type="text">
<input id="3" type="text">
<input id="4" type="text">
<input id="5" type="text">
</div>
<script type="text/javascript">
var oInput = document.getElementById('oInput'),
oChild;
for(i = 0; i < oInput.childNodes.length; i++){
oChild = oInput.childNodes[i];
if(oChild.nodeName == 'INPUT'){
alert(oChild.id);
}
}
</script>
</body>
</html>
If I put the 'script' tag in the header it didn't work because the page hadn't fully loaded and the div did not exist yet - perhaps that was your problem?
Tested in Internet Explorer 11 and Chrome.
you can try this:
var oInput = document.getElementById('oInput');
for (var ii = 0; ii < oInput.childNodes.length; ii++)
{
var childId = oInput.childNodes[ii].id;
if(typeof(childId) !== 'undefined')
alert("Child " + childId);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With