cmplieger
cmplieger

Reputation: 7351

select an array of elements and use them

Using this syntax:

var position = array($('#ipadmenu > section').attr('data-order'));

I cannot get my code to work. I have never used arrays before so im kind of lost on how to use them. (especially in jquery).

How would I make an array of all section elements and associate the value of data-order to that list. Example:

first section - data-order:1
second section - data-order:2

etc and then use that info afterwards.

Thank you!

Upvotes: 0

Views: 92

Answers (3)

Blazemonger
Blazemonger

Reputation: 92893

Since .attr just gets one attribute -- the first one found by the jQuery selector -- you need to build your array element by element. One way to do that is .each (you can also use .data to extract data attributes):

var position = new Array;
$('#ipadmenu > section').each(function() {
    position.push($(this).data('order'));
});

alert(position[0]);  // alerts "1"

This will be an indexed array, not an associative array. To build one of those (which in JavaScript is technically an object, not any kind of array) just change the inner part of your .each loop:

var position = {};
$('#ipadmenu > section').each(function(i) {
    position["section"+i] = $(this).data('order');
});

The resulting object position can now be accessed like:

alert(position['section1']); // alerts "1"

A different approach involves using jQuery.map, but since that only works on arrays, not jQuery objects, you need to use jQuery.makeArray to convert your selection into a true array first:

var position = $.map($.makeArray($('#ipadmenu > section')), function() {
    return $(this).data('order');
} );  // position is now an indexed array

This approach is technically shorter than using .each, but I find it less clear.

Upvotes: 2

Colin
Colin

Reputation: 2021

You will want to do something like this:

// Get the elements and put them in an array
var position = $('#ipadmenu section').toArray();
console.log(position);

// Loop through the array
for (var i = 0; i < position.length; i++){
  // Display the attribute value for each one
  console.log("Section " + i + ": " + $(position[i]).attr('data-order'));
}

Working example here: http://jsfiddle.net/U6n8E/3/

Upvotes: 0

Joe
Joe

Reputation: 82604

Javascript:

var orders = [];
$('#ipadmenu > section').each(function() {
    orders.push($(this).data('order'))
});

HTML:

<div id="ipadmenu">
    <section data-order="1">1</section>
    <section data-order="2">2</section>
</div>

Upvotes: 1

Related Questions