9

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" ?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Alex
  • 66,732
  • 177
  • 439
  • 641
  • Are you doing this for SEO reasons? Changes made client side won't be taken into account for most search engine spiders. – SavoryBytes Apr 07 '11 at 23:37
  • no, I want to group image links into groups based on their container, and `rel` is used by a lightbox plugin to identify galleries – Alex Apr 07 '11 at 23:41

5 Answers5

16

Short 'n sweet:

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

You can try it here.

karim79
  • 339,989
  • 67
  • 413
  • 406
3

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.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
1
var toModify = $('#xxx'); /* or how ever you identify you link */
var currentAttr = toModify.attr('rel');
if(currentAttr != 'ignore'){
    toModify.attr('rel', currentAttr + '_asd');
}
Matt Greer
  • 60,826
  • 17
  • 123
  • 123
sauerburger
  • 4,569
  • 4
  • 31
  • 42
1

Using just attr:

var add = "some rel to add";

$('a[rel!="ignore"]').attr('rel', function (i, old) {
    return old ? old + ' ' + add : add;
});
David Tang
  • 92,262
  • 30
  • 167
  • 149
1

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);
});
matt
  • 9,113
  • 3
  • 44
  • 46