Reputation: 2549
Okay - So this might be really simple but I'm pretty new to anything outside of HTML and CSS so I thought it's time I ask :)
So what I want to do is take the contents from a new attribute and add it to the href attribute.
What I have:
<div id="testDiv">
<a href="" newAttr="12345">LINK</a>
</div>
$('#testDiv a').attr('href',newAttr+'.extension');
And the outcome I want is:
<div id="testDiv">
<a href="12345.extension" newAttr="12345">LINK</a>
</div>
Am I missing something really obvious here or am I miles away?
Any help would be great!
Thanks, Nick
*EDIT - I was missing an equals sign in this post, not my actual code - Rookie :)
Upvotes: 0
Views: 54
Reputation: 38102
You can also use attr() to get the value of an attribute:
$('#testDiv a').attr('href', function (i, attr) {
return $(this).attr('newAttr') + '.extension'
});
Btw, you're missing =
inside your HTML markup:
<a href="12345.extension" newAttr="12345">LINK</a>
// ----------------------------- ^ here
EDIT: i
is the index position of your anchor in the set of anchors inside div with id testDiv
, so in your case it'll be 0
since only one anchor there. In this case, i
is not compulsory since you don't need to use it at all.
In the other hand, attr
will return the old href
value of your anchor. This one is also not needed here since you need the value of newAttr
not the href
value, so actually you can just leave both of them as blank:
$('#testDiv a').attr('href', function () {
return $(this).attr('newAttr') + '.extension'
});
Upvotes: 3
Reputation: 388316
You need to use the a variant of the attribute setter which takes a function as a handler callback
$('#testDiv a').attr('href', function (i, attr) {
return $(this).attr('newAttr') + '.extension'
});
Demo: Fiddle
Upvotes: 2
Reputation: 1654
Aren't you just missing the equal sign for the newAttr?
<div id="testDiv">
<a href="12345.extension" newAttr"12345">LINK</a>
</div>
should be
<div id="testDiv">
<a href="12345.extension" newAttr="12345">LINK</a>
</div>
Upvotes: 0