Reputation: 25
What is the best way to change a link like etc this:
<a href="replacethislink">button</a>
to
<a href="#" class="replaced">button</a>
With either js or jQuery?
Upvotes: 0
Views: 39
Reputation: 859
Using javascript (modern browser) :
var linkToReplace = document.querySelectorAll('a[href="replacethislink"]');
linkToReplace.setAttribute("href", "#");
linkToReplace.setAttribute("class", "replaced");
Using javascript (older browser) :
var linkToReplace = null;
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
if (links[i].getAttribute("href") == "replacethislink") {
linkToReplace = links[i];
}
}
if(linkToReplace) {
linkToReplace.setAttribute("href", "#");
linkToReplace.setAttribute("class", "replaced");
}
Using jQuery :
var linkToReplace = $('a[href="replacethislink"]');
linkToReplace.attr("href", "#");
linkToReplace.addClass("replaced");
Upvotes: 0
Reputation: 115222
You can use,
attr()
for updating href
attributeaddClass()
for adding the class$('a[href="replacethislink"]').attr('href', '#').addClass('replaced');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a href="replacethislink">button</a>
Upvotes: 1