jQuery - add/append value to "rel" attribute
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 exi开发者_JAVA百科sting value/values?
Also how can I skip any elements with that have a certain rel attribute, like rel="ignore"
?
Short 'n sweet:
$("a[rel!='ignore']").each(function() {
this.rel += 'theValue';
});
You can try it here.
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.
var toModify = $('#xxx'); /* or how ever you identify you link */
var currentAttr = toModify.attr('rel');
if(currentAttr != 'ignore'){
toModify.attr('rel', currentAttr + '_asd');
}
Using just 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);
});
精彩评论