Alice
Alice

Reputation: 331

Get the nth child of a div by pure JavaScript

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!

Upvotes: 19

Views: 49264

Answers (3)

sphire
sphire

Reputation: 596

You might be looking for NodeList.item():

var elements = document.getElementById('myDiv').children
elements.item(n)

See: NodeList.item()

Upvotes: 31

Slai
Slai

Reputation: 22876

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>

Upvotes: 10

brk
brk

Reputation: 50291

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>

Upvotes: 1

Related Questions