Reputation: 141
I'm trying to get a text link to change when clicking on it.
This is my code
if (document.getElementById("morecat").innerHTML === '1')
document.getElementById("morecat").innerHTML = '2';
else {
document.getElementById("morecat").innerHTML = '1';
}
<a id="morecat" >1</a>
However, it's not working, can any of you see the problem?
Upvotes: 0
Views: 184
Reputation: 26161
You have to define a function named changeText
to be used as the event listener. Besides you shouldn't make unnecessary getElementById
calls. And for a change you may use a logical short circuit in the place of if then else
block. Another thing to mention is to check the textContent
property instead of innerHTML
. Such as;
function changeText(){
var mc = document.getElementById("morecat");
mc.textContent === "1" && (mc.textContent = "2");
}
<a id="morecat" onClick="changeText()" >1</a>
Upvotes: 0
Reputation: 29431
It works as it should:
<a id="morecat" >1</a>
is the string 1
if (document.getElementById("morecat").innerHTML === '1')
it set the content to the string 2
2
is displayedI've added a timer to "see" it change:
setTimeout(function(){
console.log("morecat value is " + document.getElementById("morecat").innerHTML);
if (document.getElementById("morecat").innerHTML === '1'){
document.getElementById("morecat").innerHTML = '2';
}
else {
document.getElementById("morecat").innerHTML = '1';
}
console.log("morecat value is " + document.getElementById("morecat").innerHTML);
}, 3000);
<a id="morecat">1</a>
Upvotes: 0
Reputation: 8059
You need to wrap your script inside the function you assign to onClick().
function changeText(){
if (document.getElementById("morecat").innerHTML === '1'){
document.getElementById("morecat").innerHTML = '2';
}
else {
document.getElementById("morecat").innerHTML = '1';
}
}
<a id="morecat" onClick="changeText()" >1</a>
Upvotes: 1
Reputation: 30739
You have to write that code inside the changeText
function like this
function changeText(){
if (document.getElementById("morecat").innerHTML === '1'){
document.getElementById("morecat").innerHTML = '2';
}
else {
document.getElementById("morecat").innerHTML = '1';
}
}
<a id="morecat" onClick="changeText()" >1</a>
Upvotes: 0
Reputation: 4401
You need to wrap it in a changeText()
method call.
function changeText() {
if (document.getElementById("morecat").innerHTML === '1')
document.getElementById("morecat").innerHTML = '2';
else {
document.getElementById("morecat").innerHTML = '1';
}
}
<a id="morecat" onClick="changeText()">1</a>
Upvotes: 0