Question

I am tying to change the href link using JavaScript. In my example I would like to change the url path from "linktwo.html" to "problem3.html.

I know that there are probably easier ways of doing this, but this is for practice purposes.

Using my example as below, what am I doing wrong to change the href?

HTML:

<body onload="changeLink()">
<div id="p">
<h1> <a href="linkone.html"> first link </a></h1>
</div>
<div id ="q">
<a href="linktwo.html"> second link </a>
</div>

Javascript:

<script type="text/javascript">
function changeLink(){
document.getElementById("q").href.innerHTML="problem3.html";
}
</script>
Was it helpful?

Solution

Option One : Change the Java Script as below

<script type="text/javascript">
function changeLink(){
document.getElementById("q").href.innerHTML="<a href="problem3.html"> second link </a>";
}
</script>

Option Two : change the code as below

HTML :

<body onload="changeLink()">
<div id="p">
<h1> <a id ="p1" href="linkone.html"> first link </a></h1>
</div>
<div id ="q">
<a id ="q1" href="linktwo.html"> second link </a>
</div>

JAVA SCRIPT :

<script type="text/javascript">
function changeLink(){
document.getElementById("q1").removeAttribute("href");
document.getElementById("q1").setAttribute("href","problem3.html");
}
</script>

OTHER TIPS

Please check following code

<script type="text/javascript">
  function changeLink(){
    document.getElementById("q").href ="problem3.html";
  }
</script>

First, you should put the ID on the link itself, not the containing div.

<a href="linktwo.html" id="my_link"> second link </a>

Then, you should use the href property without innerHTML.

function changeLink(){
    document.getElementById("my_link").href = "problem3.html";
}

Give an id for the href

</head>
<body onload="changeLink()">
<div id="p">
<h1> <a href="linkone.html"> first link </a></h1>
</div>
<div id ="secondDiv">
<a href="test.html" id="q"> second link </a>
</div>

and remove the innerHTML part from the javascript:

<script type="text/javascript">
        function changeLink(){
            document.getElementById("q").href = "problem3.html";
}
</script>

You can also do:

<a id="changeurl" href="linktwo.html"> second link </a>

Give your anchor an id and then in the script area:

 link = document.getElementById('changeurl');
    link.removeAttribute('href');
    link.setAttribute('href','problem3.html');

First you get the object. Then you remove the current href attribute. After that you can add a new one! Hope this helps and better answers your question.

Thank you all for the helpful information! Further experimenting resulted in me coming up with changing my javascript to this.

function changeLink(){
document.getElementById("q").childNodes[1].href="problem3.html";

Not sure if this is practical or not but was an added solution to everyones solutions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top