Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 698
Alice Avatar asked Jan 06 '18 16:01

Alice


People also ask

How do I select a specific child in Javascript?

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.

How do you select the nth 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.

What is the nth child () selector used for?

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.


3 Answers

You might be looking for NodeList.item():

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

See: NodeList.item()

like image 140
sphire Avatar answered Oct 19 '22 08:10

sphire


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>
like image 44
Slai Avatar answered Oct 19 '22 10:10

Slai


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>
like image 43
brk Avatar answered Oct 19 '22 08:10

brk