... ... ... Some may have ...">

JQuery - add / add value to attribute "rel"

I have a set of random links, for example:

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

Some may have a rel attribute, and some may not.

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

Also, how can I skip any elements that have a specific rel attribute, for example rel="ignore" ?

+8
javascript jquery html rel
source share
5 answers

Short 'sweet:

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

You can try it here.

+16
source share

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 anchors adding your value. If rel does not exist, curRel will be just an empty string, so the code will not break.

+2
source share
 var toModify = $('#xxx'); /* or how ever you identify you link */ var currentAttr = toModify.attr('rel'); if(currentAttr != 'ignore'){ toModify.attr('rel', currentAttr + '_asd'); } 
+1
source share

Using only attr :

 var add = "some rel to add"; $('a[rel!="ignore"]').attr('rel', function (i, old) { return old ? old + ' ' + add : add; }); 
+1
source share

A bit verbose, but this should do it (http://jsfiddle.net/dGGFN/):

 var myValue = 'abc'; $.each($('a'), function(idx, item) { var a = $(item); var rel = $(a).attr('rel'); $(a).attr('rel', rel + myValue); }); 
+1
source share

All Articles