JAVASCRIPT var lis...">

Get id of first input inside div using javascript

HTML

<div id="div-1"> <input id = "input1" > </div> <p id="demo"></p> 

JAVASCRIPT

 var list = document.getElementById("div-1").firstChild.id; document.getElementById("demo").innerHTML = list; 

Output i get

 Undefined 
+5
source share
4 answers

The correct property you should use is firstElementChild

 var list = document.getElementById("div-1").firstElementChild.id; document.getElementById("demo").innerHTML = list; 

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

+2
source

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 .

 // 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> 
+4
source

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.

 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> 
+2
source

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.

 document.querySelector('#demo').innerHTML = document.querySelector('#div-1 > *:first-child').id 
 <div id="div-1"> <input id = "input1" > </div> <p id="demo"></p> 
+1
source

Source: https://habr.com/ru/post/1269346/


All Articles