1

I need help converting this jquery loop to a js loop that behaves similar to the each loop but the object properties should be inserted with pure js as I have to query like 2000 elements in the DOM and I need to increase performance a bit.

$(".single-category li").each(function(){
    store_games.push({
        skin_id  : $(this).attr('data-id'), 
        category : $(this).parent().attr('data-super-category'),
        position : $(".single-category li").index(this),
    }); 
});

TO 

var sc = document.querySelectorAll(".single-category li");
var len = sc.length - 1;
for (var i = 0;  i <= len; i++) {
    store_games.push({
        skin_id  : $(this).attr('data-id'), 
        category : $(this).parent().attr('data-super-category'),
        position : $(".single-category li").index(this),
    });
}

Can you help?

For the first two properties I'd do :

skin_id  : sc[i].getAttribute("data-id");

category : sc[i].parentNode.getAttribute("data-super-category")

The third one I need help with and if you see further how can I increase performance please let me know.

Mithical
  • 603
  • 1
  • 17
  • 28
  • What exactly makes you think you need to *increase performance* is there some issue being caused? And if so, why are you so sure this is the cause? Im not saying you're wrong, just wondering what your train of thought is here – Wesley Smith Dec 14 '16 at 12:51
  • Possible duplicate of [JavaScript DOM: Find Element Index In Container](http://stackoverflow.com/questions/11761881/javascript-dom-find-element-index-in-container) – Justinas Dec 14 '16 at 12:53
  • @Justinas: Not quite, in this specific usage of `index`. – T.J. Crowder Dec 14 '16 at 12:54
  • I have multiple catergories containing either subcategories with games or just simply games ...that index is saying after making the ui operations in the dom which index that game is in that certain category subcategory .My sketch: Container : - category [subcategory [subgame,subgame]],category[game,game,game] .With the jquery-ed version is takes like 2 seconds and blocking ui and around 10 second with ajax and curl added altogether. – Elvis Claudio Dec 14 '16 at 13:46
  • Any ideas ? Can you help please ? Thank you! – Elvis Claudio Dec 16 '16 at 09:16

1 Answers1

1

From the documentaton of index:

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

(my emphasis)

That means that in this specific case, you can just use i there:

position: i

(And in fact, that might well have been a useful thing to do in the jQuery version, which receives that same value as the first argument in each. The quoted jQuery code does a huge number of completely pointless DOM queries.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875