Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change link text in HTML using JavaScript

I have an html page which has a link called "open". Once the link is clicked the text "open" should change to "close". How do I do this?

like image 218
i2ijeya Avatar asked Nov 09 '09 09:11

i2ijeya


People also ask

How to change the text of a link element using JavaScript?

Use the textContent property to change the text of a link element, e.g. link.textContent = 'Replacement link text'. The textContent property will set the text of the link to the provided string, replacing any of the existing content. Here is the HTML for the examples in this article. And here is the related JavaScript code.

How to change the content of an HTML element using JavaScript?

document.getElementById("p1").innerHTML = "New text!"; A JavaScript changes the content ( innerHTML) of that element to "New text!" This example changes the content of an <h1> element: This example changes the value of the src attribute of an <img> element:

How to create a hyperlink in HTML?

The HTML <a> tag defines a hyperlink. It has the following syntax: The most important attribute of the <a> element is the href attribute, which indicates the link's destination. The link text is the part that will be visible to the reader. Clicking on the link text, will send the reader to the specified URL address.

How to use an HTML button as a link?

To use an HTML button as a link, you have to add some JavaScript code. JavaScript allows you to specify what happens at certain events, such as a click of a button: Tip: Learn more about JavaScript in our JavaScript Tutorial. The title attribute specifies extra information about an element.


2 Answers

Script

<html>
  <head>
    <script type="text/javascript">
      function open_fun() {
        document.getElementById('link').innerHTML = "<a href='javascript:clo_fun()'>CLOSE</a>";
      }
      function clo_fun() {
        document.getElementById('link').innerHTML = "<a href='javascript:open_fun()'>OPEN</a>";
      }
    </script>
  </head>
  <body>
    <div id='link'><a href='javascript:open_fun()'>OPEN</a></div>
  </body>
</html>
like image 105
sathish Avatar answered Sep 28 '22 16:09

sathish


addEventListener is not supported in IE. If you don't need other onclick events on the link, use this:

elm.onclick = function (e) {
    this.innerHTML = "close";
};
like image 26
Boldewyn Avatar answered Sep 28 '22 16:09

Boldewyn