Skip to content Skip to sidebar Skip to footer

Get Id Of First Input Inside A Div Using Javascript

HTML

JAVASCRIPT var list = document.getElementById('div-1').firstChild.id; doc

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;
<divid="div-1"><inputid="input1"></div><pid="demo"></p>

var list = document.getElementById("div-1").firstElementChild.id;
document.getElementById("demo").innerHTML = list;
<divid="div-1"><inputid="input1"></div><pid="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 themvar list = document.querySelector('#div-1 input').id;
document.getElementById("demo").innerHTML = list;
<divid="div-1"><inputid="input1"></div><pid="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;
<divid="div-1"><inputid = "input1" ><inputid = "input2" ><inputid = "input3" ></div><pid="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;

https://jsfiddle.net/sureshatta/u2q7jpk0/

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;
<divid="div-1"><inputid = "input1" ></div><pid="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
<divid="div-1"><inputid = "input1" ></div><pid="demo"></p>

Post a Comment for "Get Id Of First Input Inside A Div Using Javascript"