MarUSPT MarUSPT - 5 months ago 10
HTML Question

Change html text when click

I need some help because i don't know how to change the text more than one time:

This is my span:

<span id="demo" style="cursor: pointer;" onclick="myFunction()"><b> + </b></span>


And this is my
.js
file

function myFunction() {
document.getElementById("demo").innerHTML = "<b> - </b>";
}


In my
span
when i click in
+
it will change for
-
but if i click again it wont change to
+
how can i make that happend?

I need this because if there is the
+
means that if you click my
div
will show up, and it will change to
-
but if i click again my
div
will hide but the
-
stays there and i need to change it to
+
.

Answer

No need to change the innerHTML(As you are not updating HTML but text), just select b element using querySelector and change the textContent of it based on conditions(Conditional (ternary) Operator).

The Node.textContent property represents the text content of a node and its descendants.

function myFunction() {
  var elem = document.getElementById("demo").querySelector('b');
  elem.textContent = elem.textContent == ' - ' ? ' + ' : ' - ';
}
<span id="demo" style="cursor: pointer;" onclick="myFunction()"><b> + </b></span>