I have a div element called 'myDiv'. How can I get the nth child of 'myDiv' by DOM manipulation?
Markup:
function revealNibble(n) {
// Do something here...
var elements=document.getElementById('myDiv').children;
for(var i=1; i<=elements.length; i++) {
if(n === i) {
var output = elements[i].innerText || elements[i].textContent;
document.getElementById('output').innerHtml = output;
}
}
}
<body>
<div id="myDiv">
<p>One</p>
<p>Two</p>
<p>Three</p>
<p>Four</p>
<p>Five</p>
</div>
<hr/>
<div id="output"></div>
</body>
My code does not work!
Select the parent element whose child element is going to be selected. Use . querySelector() method on parent. Use the className of the child to select that particular child.
The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.
You might be looking for NodeList.item()
:
var elements = document.getElementById('myDiv').children
elements.item(n)
See: NodeList.item()
var n = 4
console.log( myDiv.children [n - 1] ) // Nth Element <p>Four</p>
console.log( myDiv.childNodes[n - 1] ) // Nth Node <p>Two</p>
<body>
<div id="myDiv">
<p>One</p>
<p>Two</p>
<p>Three</p>
<p>Four</p>
<p>Five</p>
</div>
<hr/>
<div id="output"></div>
</body>
Change to innerHTML
function revealNibble(n) {
//Do something here...
var elements = document.getElementById('myDiv').children;
for (var i = 1; i <= elements.length; i++) {
if (n === i) {
var output = elements[i].innerHTML || elements[i].textContent;
document.getElementById('output').innerHTML = output; // changed here
}
}
}
revealNibble(3)
<div id="myDiv">
<p>One</p>
<p>Two</p>
<p>Three</p>
<p>Four</p>
<p>Five</p>
</div>
<hr/>
<div id="output"></div>
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