1

I want to add a rel attribute of the element matching the array, so for example the array is:

var targetVal = ['1','2','4'];

And 5 elements with the same class:

<a class="link" href="1.html">
<a class="link" href="2.html">
<a class="link" href="3.html">
<a class="link" href="4.html">
<a class="link" href="5.html">

I want to target the 2nd, 3rd and 5th line with a rel attribute.

 $(".link").each(function(index) {
       $(this).attr("rel", "group");
    });

How can I make the above script index through based on the array?

3 Answers 3

1
var targetVal = ['1','2','4'];

$.each(targetVal, function(index, val) {
       console.log(val);
       $('.link').eq(val).attr("rel", "group");
});

jsFiddle example http://jsfiddle.net/roXon/T7zR8/

Sign up to request clarification or add additional context in comments.

Comments

1

You can use $.each() to iterate over your array, and eq() to get the link at a specific index:

var $links = $(".link");
$.each(targetVal, function(value) {
    $links.eq(value).attr("rel", "group");
});

Comments

0

This would be more optimal, only evaluating the set of links once, and directly accessing that list instead of using .eq():

var targetVal = [1, 2, 4];
var links = $('.link');
$.each(targetVal, function(i, n) {
    links[n].setAttribute('rel', 'group');
});

or, on newer browsers, and without jQuery:

var targetVal = [1, 2, 4];
var links = document.querySelectorAll('.link');
while (targetVal.length) {
    links[targetVal.pop()].setAttribute('rel', 'group');
}

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.