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>
>Solution :
This should toggle the button text as expected. The content variable does not update.
<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(e){
const content = e.target.innerHTML
if (content === "text1") {
e.target.innerHTML = "text2"
} else {
e.target.innerHTML = "text1"
}
}
</script>
</body>
</html>