Select divs separate, with same id
How to select divs that are with same name, but to select them separate ?
<div id='wholestuff'>
<div id='item'>
info something
</div>
<div id='item'>
info something
</div>
<div id='item'>
else
</div>
<div id='item'>
stuff
</div>
<div id='item'>
info something
</div>
<div id='item'>
info something
</div>
</div>
And i want to select the second div with id item .. how 开发者_运维技巧to do that ?
It's not advisable to give different elements the same id. Id's have to be unique. You are grouping your 'items' within div#wholestuff, so if you want the second element, that would be:
document.getElementById('wholestuff').getElementsByTagName('div')[1];
The answer is not to use the same ID for more than one element on the page - it must be unique. Use unique IDs and then it will be easy to select the element you want.
Using the same ID for multiple elements is not compliant, and can cause unpredictable behavior in different browsers.
It looks like your can use a list in that case
<ul id='wholestuff'>
<li>
info something
</li>
<li>
info something
</li>
<li>
info something
</li>
<li>
info something
</li>
</ul>
And there's a nth-child selector in css too. To select the third one your need:
#wholestuff li:nth-child(3) { }
jQuery does it like:
$('#item:eq(2)')
But you really shouldn't have multiple DIVs with identical IDs. You should use class names instead. IDs should always be unique
精彩评论