Markup code:
<div id="elements">
<div>
<a href="#">text</a>
<a href="#">text</a>
<a href="#">text</a>
</div>
<div>
<a href="#">text</a>
<a href="#">text</a>
<a href="#">text</a>
</div>
<div>
<a href="#">text</a>
<a href="#">text</a>
</div>
</div>
Please tell me how can I get an array of all elements of the div
, so that later, it is p开发者_开发知识库ossible to address an array of options?
Such as:
divs[0]
links[1]
See https://api.jquery.com/toArray/
$( "li" ).toArray()
This works great in cases like
$( "li" ).toArray().each( function(li) {
console.log('do something with this list item', li);
})
or if you really want
$( "li" ).toArray()[0]
Demo
var divs = $('#elements div');
var links = $('#elements div a');
- If you want the DOM elements, then you can access them with the array style like
divs[0]
orlinks[2]
. - If you want to get the specific jQuery object, you can access them with
divs.eq(0)
orlinks.eq(1)
.
$('#elements div').eq(0) // first div
$('#elements div a').eq(1) // second anchor in group of divs
Without the .eq()
you have a collection of elements, the .eq
just singles the elements out.
wrapper = document.getElementById('elements');
divs = wrapper.getElementsByTagName('div');
links = [];
for (i = 0; i < divs.length; i++) {
links[i] = divs[i].getElementsByTagName('a');
}
divs will now be an array of the divs inside of your "elements" div. Links is now a two dimensional array, where the first index refers to the div inside your "elements" div, and the second index refers to the "a" tags inside that div.
links[2][1]
will refer to the element denoted below:
<div id="elements">
<div>
<a href="#">text</a>
<a href="#">text</a>
<a href="#">text</a>
</div>
<div>
<a href="#">text</a>
<a href="#">text</a>
<a href="#">text</a>
</div>
<div>
<a href="#">text</a>
<a href="#">text</a> //this one
</div>
</div>
Or also, and I believe this is more accurately what you asked for:
$("#elements div:eq(0) a:eq(1)")
$("#elements a")
$("div a")
or $("a")
jQuery Selectors
精彩评论