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] 
1

6 Answers 6

16

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]
Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct answer. The accepted answer is outdated.
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).

3 Comments

I get an array of links for each div separately? $ ('# elements div [0] a'); like - something like that, just to correct it. ) I need to do the sorting. :)
@SirRoland Yes, you can do $('#elements div:eq(0) a');.
if I write: var links=$('#elements div:eq(0) a').length; alert(links); // = 0
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.

Comments

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>

Comments

1

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

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

Comments

0
$("#elements a")

$("div a")

or $("a")

jQuery Selectors

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.