hhffh fhfg
hhffh fhfg

Reputation: 141

Why is this .innerHTML script not working?

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

Answers (5)

Redu
Redu

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

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

It works as it should:

  • innerHTML of <a id="morecat" >1</a> is the string 1
  • given your condition : if (document.getElementById("morecat").innerHTML === '1') it set the content to the string 2
  • 2 is displayed

I'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

Oleh Rybalchenko
Oleh Rybalchenko

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

Ankit Agarwal
Ankit Agarwal

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

Sajal
Sajal

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

Related Questions