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" sho开发者_StackOverflow社区uld change to "close". How do I do this?
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>
<a href="" onClick="this.innerHTML = 'close'">Open</a>
You could also call some type of toggle function for swapping the text on multiple clicks.
function toggle(lnk_obj){
lnk_obj.innerHTML = (lnk_obj.innerHTML == 'close') ? 'open' : 'close' ;
}
<a href="" onClick="javascript:toggle(this);">Open</a>
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 elm is the link:
elm.addEventListener("click", function(){
this.innerHTML = "close";
}, true);
Say you have link:
<a id="link" href="https://www.example.com" onclick=change(event)>open</a>
Then you can use the following javascript code
const change = (event) => {
const link = document.getElementById("link");
link.text = link.text === 'open' ? 'close' : 'open';
event.preventDefault();
}
So to change label value you can simply use the text
property of the element:
link.text = 'closed'; // now the text on the href will be 'closed'
I will add a a fiddle to demonstrate the workings of this simple code.
Also check documentation here on MDN for the text property on an HtmlAnchorElement
:
HTMLAnchorElement.text
Is a DOMString being a synonym for theNode.textContent
property.
So instead of changing the text node you can set this text property directly. This is merely a simple code example for demonstrating the working. You could for example also grab the anchor element from the event...
Note: Setting innerHTML
(advised in other answers) is not considered safe since it can be used for injecting malicious code into the DOM.
精彩评论