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" ?
Short 'sweet:
$("a[rel!='ignore']").each(function() { this.rel += 'theValue'; }); 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.
var toModify = $('#xxx'); /* or how ever you identify you link */ var currentAttr = toModify.attr('rel'); if(currentAttr != 'ignore'){ toModify.attr('rel', currentAttr + '_asd'); } Using only attr :
var add = "some rel to add"; $('a[rel!="ignore"]').attr('rel', function (i, old) { return old ? old + ' ' + add : add; }); 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); });