I’m trying to check if button contains certain string when I click on it, and if it contains, for example "text1" I want to replace it with "text2" and vice versa.
Thank you in advance.
Edit:
To simplify everything, how can I change the text of button if it contains certain word when I click on it.
Here is the sample code:
<html>
<body>
<button id="btn">text1</button>
<p id="result"></p>
<script>
let btn = document.getElementById("btn");
let content = btn.innerHTML;
document.getElementById("btn").onClick=function(){
if(content.trim()==="text1"){
document.getElementById("btn").innerHTML ="text2";
}
}
</script>
</body>
</html>
2
Answers
You could add the event to an eventlistener and switch the text on click.
This should toggle the button text as expected. The
content
variable does not update.