Reputation: 1417
I am struggling to find a solution of replacing my attribute with another.
My HTML is:
<a href="#" external>link</a>
I want to replace "external" with target="_blank"
Is it doable?
Upvotes: 1
Views: 59
Reputation: 241208
You don't need jQuery for that.
Just iterate over the anchor elements with the external
attribute using the selector a[external]
and remove the external
attribute and set the target
attribute:
Array.prototype.forEach.call(document.querySelectorAll('a[external]'), function(a) {
a.removeAttribute('external');
a.setAttribute('target', '_blank');
});
For what it's worth, if you want the jQuery alternative, use:
$('a[external]').each(function () {
$(this).removeAttr('external');
$(this).attr('target', '_blank');
});
Upvotes: 3
Reputation: 2830
Correct me if I'm wrong, but this doesn't do what the OP describes, even if it does what he wanted. He said he wanted to replace external with target='_blank'. This removes external and adds target='_blank' regardless of whether or not that anchor had an external attribute. The below takes your code and checks for the existence of the external attribute before doing anything.
Array.prototype.forEach.call(document.querySelectorAll('a'), function(a) {
if (a.getAttribute("external") != null) {
a.removeAttribute('external');
a.setAttribute('target', '_blank');
}
});
Upvotes: 1