Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get id of first input inside a 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;

The output i get is

Undefined
like image 589
Ng21 Avatar asked Jun 29 '17 18:06

Ng21


People also ask

How do I get the element inside a div?

We can use document. querySelector on to select a div and then select an element within it with the given class after that. We just call querySelector on the element with the ID mydiv to select items inside that div. Therefore, innerDiv is the div with the class myclass .

Can JavaScript input id?

The id allows JavaScript to easily access the <input> element. It is also used to point to a specific id selector in a style sheet. Tip: id is a global attribute that can be applied to any HTML element.

How do I find the ID of a section?

To find the ID of a particular Section, click on the 'Edit Section' option. Then head over to the 'Advanced' tab of that particular Section. You will find the Section ID inside the 'CSS ID' field.


2 Answers

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>
like image 143
Pranav C Balan Avatar answered Nov 14 '22 22:11

Pranav C Balan


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>
like image 25
Scott Marcus Avatar answered Nov 14 '22 22:11

Scott Marcus