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"
?
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.
Short 'n sweet:
$("a[rel!='ignore']").each(function() {
this.rel += 'theValue';
});
You can try it here.
var toModify = $('#xxx'); /* or how ever you identify you link */
var currentAttr = toModify.attr('rel');
if(currentAttr != 'ignore'){
toModify.attr('rel', currentAttr + '_asd');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With