12

I'm using Array.prototype.map.call to store in an array a bunch of node list objects:

function getListings() {
    return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e) {
         return {
             rectangle: e.getBoundingClientRect();
         }
    }
}

However, I also want to store the order in which this elements appear in the DOM, and I don't know how to do that.

I know that I'm storing this in an array, and the order would be the index of the array. For example:

var listings = getListings();
console.log(listings[0]); // rank #1
console.log(listings[1]); // rank #2
// etc...

but I'm inserting the json object in a database, and the easiest way to store the "rank" information is by creating a property "rank" in my object, but I don't know how to get the "index" of the current array.

Something like:

function getListings() {
    return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e) {
         return {
             rectangle: e.getBoundingClientRect(),
             rank: magicFunctionThatReturnsCurrentIndex() // <-- magic happens
         }
    }
}

Any help pointing me to the right direction will be greatly appreciated! Thanks

2
  • I think document.querySelectorAll('li.g') should return elements right in the correct order, i.e. how they appear in DOM. Commented Nov 15, 2013 at 14:47
  • Yes it does, but is there any way to get the numerical value? I have the elements in the current order, but I want to have an attribute in my JSON object with its numerical value. Commented Nov 15, 2013 at 14:48

1 Answer 1

22

The MDN documentation says:

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

So

function getListings() {
    return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e, rank) { // magic 
         return {
             rectangle: e.getBoundingClientRect(),
             rank: rank // <-- magic happens
         }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I read that page over and over, and for whatever reason I never noticed that the index was also being passed. Thanks!

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.