How can I get all children of a html tag with a certain name?
Let's assume I have a <div>
which looks like this
<div id=test>
<input name=test1/>
<input name=test2/>
</div>
if I have the div element, how can I get any child with name test1 or test2? I tried
div.getElementsByName('test1')
but that does not work?
In order to get the first child element of a node, it is required to use the firstChild property of the element. In the described syntax, the variable firstchild will hold the value of the first child element, and the parentElement is the parent node of which we are trying to get the first child element value.
Select the child element of parent element. Select the parent by.parentNode property. Use Array.prototype.indexOf.call (Children_of_parent, current_child) to get the index. Example 1: This example using the approach discussed above.
In JavaScript HTML DOM, we can easily get the child element of a parent element using the childNodes property. Suppose we have div element and a child div inside this just like you can see below with some ID:
More "Try it Yourself" examples below. The childNodes property returns a collection of a node's child nodes, as a NodeList object. The nodes in the collection are sorted as they appear in the source code and can be accessed by index numbers.
<div id=test>
<input name="test1" />
<input name="test2" />
</div>
Be aware, that getElementsByName
returns a live NodeList of matching elements which is an array-like object even if you expect and receive one result.
USING THE
id
ATTRIBUTE: If you know your name will be unique in the whole document, I'd advise using anid
instead of the the name or class attributes. Doing so would allow this:Html:
<div id=test> <input id="test1" name="test1"/> <input id="test2" name="test2"/> </div>
JavaScript:
document.getElementById("test1");
USING
document.querySelector
:If you still need to use the name attribute then you can use
document.querySelector
with the following selection parameter:document.querySelector('div > input[name="test1"]')
document.querySelector
returns the first element in the document that matches the selection parameter.In the example above it says, return the first element that is an
input
with name attribute equal to "test1" that is a child of adiv
.
document.querySelector('input[name="test1"]')
Or if you want to target a specific child of a specific element:
var test = document.querySelector('#test')
var test1 = test.querySelector('input[name="test1"]');
window.console.log(test1)
Option #1:
var x = document.getElementsByName("test1");
Option #2:
var x = document.querySelectorAll("input[name='test1']");
In both cases you'll get array as a response: x[0], x[1], ...
div.getElementsByName('test1')
doesn't work because getElementsByName is a method of document object, you may only call document.getElementsByName('elementName').
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