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?
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.
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:
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.
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.
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>
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";
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With