jQuery - add/append value to "rel" attribute
Asked Answered
U

5

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

Urolith answered 7/4, 2011 at 23:17 Comment(2)
Are you doing this for SEO reasons? Changes made client side won't be taken into account for most search engine spiders.Shanty
no, I want to group image links into groups based on their container, and rel is used by a lightbox plugin to identify galleriesUrolith
S
16

Short 'n sweet:

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

You can try it here.

Spieler answered 7/4, 2011 at 23:30 Comment(1)
...and yes it will add a rel to anchors without rel attributes.Spieler
E
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.

Eliott answered 7/4, 2011 at 23:26 Comment(0)
S
1
var toModify = $('#xxx'); /* or how ever you identify you link */
var currentAttr = toModify.attr('rel');
if(currentAttr != 'ignore'){
    toModify.attr('rel', currentAttr + '_asd');
}
Schleicher answered 7/4, 2011 at 23:24 Comment(0)
E
1

Using just attr:

var add = "some rel to add";

$('a[rel!="ignore"]').attr('rel', function (i, old) {
    return old ? old + ' ' + add : add;
});
Everard answered 7/4, 2011 at 23:31 Comment(0)
B
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);
});
Benthamism answered 7/4, 2011 at 23:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.