I have lots of page with button. I want to replace some specific links with another link.
Here is the HTML code
<button onclick="changeURL()">change link</button>
<button onclick="location.href='https://google.com'" id="link">go to link</button>
I tried to add this script but it’s not working.
<script>
function changeURL(){
var newURL = "https://youtube.com";
document.getElementById("link").href = newURL;
}
</script>
3
Answers
This is good code.
Perhaps
getElementById(link)
does not exist.The Problem i see is that you try to change the value of href, but the Button dont supports hrefs.
try this:
If you have many buttons with different ids you can wrote the name in your function, like this:
If there are lots of buttons on a page that need to have their intended target modified perhaps the following will be of interest. You cannot have duplicate ID attributes and expect any Javascript code that uses the ID to behave correctly. You could modify that ID and make it a
dataset
property, such asdata-id='link'
and that is perfectly valid and makes sense when trying to identify more than one element as shown below.The button that is used to change the target of the buttons calls
document.querySelectorAll
to identify any/all buttons with thedata-id
property and then iterates through that nodelist to modify the event handler assigned to each button.I added the
data-name
attribute only to indicate different buttons – it plays no part in the modification code