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
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 .
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.
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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With