5

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 possible to address an array of options?

Such as:

divs[0]  
links[1] 
Shef
  • 44,808
  • 15
  • 79
  • 90
SirRoland
  • 187
  • 2
  • 2
  • 10

6 Answers6

13

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]
Paul Schwarz
  • 1,828
  • 1
  • 15
  • 24
9

Demo

var divs = $('#elements div');
var links = $('#elements div a');
  1. If you want the DOM elements, then you can access them with the array style like divs[0] or links[2].
  2. If you want to get the specific jQuery object, you can access them with divs.eq(0) or links.eq(1).
Shef
  • 44,808
  • 15
  • 79
  • 90
8
$('#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.

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
1
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>
mowwwalker
  • 16,634
  • 25
  • 104
  • 157
1

Or also, and I believe this is more accurately what you asked for:

$("#elements div:eq(0) a:eq(1)")

maxijb
  • 541
  • 4
  • 13
0
$("#elements a")

$("div a")

or $("a")

jQuery Selectors

Nikola K.
  • 7,093
  • 13
  • 31
  • 39
Mirko
  • 1,014
  • 9
  • 11