0

I have a website with a couple of elements like this:

<g class="box" rel="1">...</g>
<g class="box" rel="2">...</g>
<g class="box" rel="3">...</g>
<g class="box" rel="4">...</g>
<g class="box" rel="5">...</g>

In my code I want to change some attributes of these elements in a loop. What I have done at first was this (it works fine for me):

for(var i = 0, l = relValList.length; i < l; i+=1){
    $(".box[rel=" + relValList[i] + "]").children().first().attr("fill","#000000");
}

Now I have read a jQuery best practices article, where i found something called caching to increase the performance.

So I try it.

//call this when page loaded
var boxes = $(".box");

//the good old loop
for(var i = 0, l = relValList.length; i < l; i+=1){
   //here is my problem
   boxes ????
}

What is the best way to get a specific element from boxes by its rel attribute?

Thanks!

0

2 Answers 2

2

You can use filter method, it iterates through the selected elements and returns the matching ones. filter method is much faster than chained strings selectors.

var $boxes = $(".box"),
    $goldenOnes = $boxes.filter('[rel="golden"]');
Sign up to request clarification or add additional context in comments.

Comments

0

Try filter. It applies a selector to an existing jQuery selection.

box.filter("[rel=" + relValList[i] + "]").children().first().attr("fill","#000000");

Alternatively, you do not even have to loop over the boxes. You can match the first child of every box having a rel attribute like this:

$('.box[rel] :first-child').attr("fill","#000000");

2 Comments

It is. Looking up by class otherwise happens every iteration, like this it happens just once. Once is faster than n times.
Thank you!! This is exactly what I'm looking for!! Works perfect and I got a much better performance (tested on mobile Safari, iPad 1).

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.