Get id of first input inside div using javascript
firstChild (which retrieves the first child of a node) can be the text of the node immediately before the input element (space), and it has no id property, so the output will be undefined .
To fix the problem, use Element#querySelector to get the input element or use firstChildElement (not widely supported, which returns the first child).
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 an item using Document#querySelector .
The simplest answer:
var inputID = document.querySelector("#div-1 input").id; Because querySelector returns the first node that matches the provided CSS selector. You can essentially find only one element that you need to find the div , and then look for its first child.
It is simpler and will work better.
If you need an element, you can 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 can use #div-1 > *:first-child to select the first child, whatever it is.