Selecting second children of first div children in javascript [duplicate]

故事扮演 提交于 2019-11-27 02:33:35

问题


I have an html that look something like this:

<div id="mainDiv"> <-- I have this
    <div>
        <div></div>
        <div></div> <-- I need to get this
    </div>
    <span></span>
    <more stuff />
</div>

i am using:

var mainDiv = document.getElementById('mainDiv');

because I need that div in a var, but i also need to get that second div on the first div inside mainDiv into a variable.

How could I do it in a simple cross-browser way?


回答1:


Assuming that structure is static you can do this:

var mainDiv = document.getElementById('mainDiv'),
    childDiv = mainDiv.getElementsByTagName('div')[0],
    requiredDiv = childDiv.getElementsByTagName('div')[1];

Further reading: .getElementsByTagName() (from MDN).




回答2:


 var mainDiv = document.getElementById('mainDiv');
 var x = mainDiv.children[0].children[1];

or

 var mainDiv = document.getElementById('mainDiv');
 var x = mainDiv.getElementsByTagName('div')[0].getElementsByTagName('div')[1];



回答3:


I would pick jQuery and end up with something like this:

var getThis = $('#mainDiv > div:eq(0) > div:eq(1)');

Fiddle




回答4:


I would go simply with just one line of vanilla code.

Works for any elements, is not limited to the tag names you have in the structure. But the number of elements and the hierarchy must be preserved.

var requiredDiv = document.getElementById('mainDiv').firstChild.firstChild.nextSibling;



回答5:


var mainDiv = document.getElementById('mainDiv');
var div = maindiv.getElementsByTagName('div')[2];//third div

http://jsfiddle.net/MGVw8/




回答6:


You know there is querySelector now ?

console.log(
  mainDiv.querySelector(':nth-child(1) > :nth-child(2)'))
<div id="mainDiv">
  <div>
    <div></div>
    <div>come get me</div>
  </div>
  <!-- more stuff -->
</div>


来源:https://stackoverflow.com/questions/12048273/selecting-second-children-of-first-div-children-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!