Home > Web Front-end > JS Tutorial > How to Change the `href` Attribute of an `` Tag Using Javascript on Button Click?

How to Change the `href` Attribute of an `` Tag Using Javascript on Button Click?

Linda Hamilton
Release: 2024-10-26 12:26:29
Original
260 people have browsed it

How to Change the `href` Attribute of an `` Tag Using Javascript on Button Click?

Altering 'href' Attribute of Tag via Javascript Button Click

To modify the 'href' attribute of an tag using Javascript when a button is clicked, consider the following scenarios:

1. Preventing Page Reload

By default, clicking an empty tag reloads the page. To prevent this:

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

2. Disabling Scroll

Alternatively, you can use this to prevent scrolling to the top of the page:

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

3. Returning False in Function

You can also return false in the f1() function and use:

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

4. Unobtrusive Method

Consider the following for a less intrusive approach:

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

<script>
  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 Using Javascript on Button Click?. 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