Home > Web Front-end > JS Tutorial > body text

How to Change the `href` Attribute of an `` Tag on Button Click with JavaScript?

Patricia Arquette
Release: 2024-10-28 16:16:02
Original
335 people have browsed it

How to Change the `href` Attribute of an `` Tag on Button Click with JavaScript?

How to Modify the Href Attribute of an Tag on Button Click Using JavaScript

Question:

How can you change the href attribute value of an tag through JavaScript on button click?

Answer:

To alter the href attribute of an tag when a button is clicked, the following methods can be employed:

Option 1: Using an Empty href

Add an empty href attribute to the tag:

<code class="html"><a href="" id="abc">jhg</a></code>
Copy after login

Option 2: Preventing Page Reload

Include the code below within the href attribute to prevent page reload:

<code class="html"><a href="#" onclick="f1();">jhhghj</a></code>
Copy after login

Option 3: Returning False from the Function

In the f1() function, return false and call it from the href like this:

<code class="html"><a href="#" onclick="return f1();">jhhghj</a></code>
Copy after login

Option 4: Unobtrusive Way

Use the following JavaScript to modify the href attribute without inline event handlers:

<code class="html"><a href="#" id="abc">jhg</a>
<a href="#" id="myLink">jhhghj</a>

<script type="text/javascript">
  document.getElementById("myLink").onclick = function() {
    document.getElementById("abc").href="xyz.php";
    return false;
  };
</script></code>
Copy after login

The above is the detailed content of How to Change the `href` Attribute of an `` Tag on Button Click with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template