denblaakop
denblaakop

Reputation: 25

Change hyperlink to something else with js or jquery

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

Answers (2)

Paul DS
Paul DS

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

Pranav C Balan
Pranav C Balan

Reputation: 115222

You can use,

  1. attr() for updating href attribute
  2. addClass() 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

Related Questions