Home > Web Front-end > JS Tutorial > How to Dynamically Update an Tag\'s href Attribute Using JavaScript?

How to Dynamically Update an Tag\'s href Attribute Using JavaScript?

Linda Hamilton
Release: 2024-10-27 00:38:02
Original
222 people have browsed it

How to Dynamically Update an  Tag's href Attribute Using JavaScript?

How to Update Tag's Href Attribute Using JavaScript

When attempting to modify an tag's href property via JavaScript upon button click, you may face difficulties. Let's explore solutions to address this issue.

First, it's crucial to provide the tag with a href value, as leaving it empty will trigger a page refresh on click. Consider the following options:

  • Assign a non-empty href value:

    <code class="html"><a href="#" id="abc">jhg</a></code>
    Copy after login
  • Prevent page scrolling:

    <code class="html"><a href="#" id="abc" onclick="f1(); return false;">jhhghj</a></code>
    Copy after login
  • Include the return false statement within the f1 function:

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

Alternatively, you can adopt the unobtrusive approach:

<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

This approach separates JavaScript from the HTML, improving code organization and adaptability.

The above is the detailed content of How to Dynamically Update an Tag\'s href Attribute Using 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