通过纯javascript获取div的第n个孩子

时间:2018-01-06 16:20:52

标签: javascript html

我有一个名为' myDiv'的div元素。我怎样才能得到'myDiv'的第n个孩子?通过DOM操作? 标记:



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;
        }
      }
    }
&#13;
 <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> 

    
&#13;
&#13;
&#13;

我的代码不起作用!!!

3 个答案:

答案 0 :(得分:4)

您可能正在寻找product.active_subscriptions

NodeList.item()

请参阅:https://developer.mozilla.org/en-US/docs/Web/API/NodeList/item

答案 1 :(得分:1)

更改为innerHTML

&#13;
&#13;
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)
&#13;
<div id="myDiv">
  <p>One</p>
  <p>Two</p>
  <p>Three</p>
  <p>Four</p>
  <p>Five</p>
</div>
<hr/>
<div id="output"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

var n = 4

console.log( myDiv.children[n - 1] )    // Nth Element

console.log( myDiv.childNodes[n - 1] )  // Nth Node
<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>