Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - add/append value to "rel" attribute

I have a set of random links, like this:

<a rel="foo"> ... </a>
...
<a> ... </a>

Some of them may have a rel attribute, some not.

How can add a rel attribute with a value to each link, and if the link already has one, then append my value to the existing value/values?

Also how can I skip any elements with that have a certain rel attribute, like rel="ignore" ?

like image 689
Alex Avatar asked Apr 07 '11 23:04

Alex


3 Answers

This should work fine:

$("a").each(function(index) {
    var curRel = $(this).attr("rel");
    if (curRel !== "ignore")
        $(this).attr("rel", curRel + " my value");
});

Simple iteration over all the anchors, appending your value. If rel doesn't exist curRel will just be empty string so the code won't break.

like image 184
Shadow Wizard Hates Omicron Avatar answered Sep 18 '22 12:09

Shadow Wizard Hates Omicron


Short 'n sweet:

$("a[rel!='ignore']").each(function() {
    this.rel += 'theValue';
});

You can try it here.

like image 41
karim79 Avatar answered Sep 19 '22 12:09

karim79


var toModify = $('#xxx'); /* or how ever you identify you link */
var currentAttr = toModify.attr('rel');
if(currentAttr != 'ignore'){
    toModify.attr('rel', currentAttr + '_asd');
}
like image 25
sauerburger Avatar answered Sep 17 '22 12:09

sauerburger