Get Id Of First Input Inside A Div Using Javascript
Solution 1:
The firstChild
(which retrieve the first child node) may be the text node just before the input element(whitespace) and it doesn't have any id
property so the output would be undefined
.
To resolve the problem, use Element#querySelector
to get the input element or use firstChildElement
(not widely supported, which retrieves the first child element) property.
var list = document.getElementById("div-1").querySelector('input').id;
document.getElementById("demo").innerHTML = list;
<div id="div-1">
<input id="input1">
</div>
<p id="demo"></p>
var list = document.getElementById("div-1").firstElementChild.id;
document.getElementById("demo").innerHTML = list;
<div id="div-1">
<input id="input1">
</div>
<p id="demo"></p>
UPDATE : Or you can directly select the element with Document#querySelector
method.
// you can use css selector with querySelector
// which only gets the first element from them
var list = document.querySelector('#div-1 input').id;
document.getElementById("demo").innerHTML = list;
<div id="div-1">
<input id="input1">
</div>
<p id="demo"></p>
Solution 2:
The simplest answer is:
var inputID = document.querySelector("#div-1 input").id;
Because querySelector
returns the first node that matches the provided CSS selector. You can essentially find just the one element you need rather that finding the div
and then looking for its first child.
This is simpler and will perform better.
var inputID = document.querySelector("#div-1 input").id;
document.getElementById("demo").textContent = inputID;
<div id="div-1">
<input id = "input1" >
<input id = "input2" >
<input id = "input3" >
</div>
<p id="demo"></p>
Solution 3:
The correct property you have to use is firstElementChild
var list = document.getElementById("div-1").firstElementChild.id;
document.getElementById("demo").innerHTML = list;
Solution 4:
If you need element you could use firstElementChild
instead of firstChild
var list = document.getElementById("div-1").firstElementChild.id;
document.getElementById("demo").innerHTML = list;
<div id="div-1">
<input id = "input1" >
</div>
<p id="demo"></p>
Or you could use #div-1 > *:first-child
to select first child element whatever it is.
document.querySelector('#demo').innerHTML =
document.querySelector('#div-1 > *:first-child').id
<div id="div-1">
<input id = "input1" >
</div>
<p id="demo"></p>
Post a Comment for "Get Id Of First Input Inside A Div Using Javascript"