Comparison going wrong

1

I saw an example comparison and I was in doubt about the reason for the operation.

In the comparison below, it removes the text and <button> and compares in the if to the check, whether it is true or false, but it never enters the true, even using === to compare. >

Apparently, at the time of getting the value it is "converting" &#709; and can not make the comparison.

function trocar(){
  valor = document.getElementById('btnTrocar').innerHTML;
  console.log(valor);
  if(valor == "Imagem &#709;"){
    document.getElementById("btnTrocar").innerHTML = "Imagem  &#706;";
    alert("Texto 1");
  }
  else{
    document.getElementById("btnTrocar").innerHTML = "Imagem  &#709;";
    alert("Texto 2");
  }
}
<button onclick="trocar()" id="btnTrocar">Imagem &#709;</button>

If this "conversion" exists:

  • What's the reason for it?
  • Why does it not treat as a "normal text"?
  • Is there any way to get this button text, without changing anything?
asked by anonymous 06.09.2018 / 16:11

1 answer

0
  

What's the reason for it?

Because this is a way to write in the code, because it is complicated to write otherwise unambiguously in the ordinary way. But it's just like it's in the code, the document is not like that, it's the same character. As HTML is one thing, as string is another.

  

Why does not it treat like a "normal text"?

It treats, you think that this is normal text, but the normal one is the character represented by the code #709 .

  

Is there any way to get this button text, without changing anything?

Of course not, if it is giving error something has to be changed. I changed and it worked:

function trocar(){
  valor = document.getElementById('btnTrocar').innerHTML;
  console.log(valor);
  if(valor == "Imagem ˅"){
    document.getElementById("btnTrocar").innerHTML = "Imagem  &#706;";
    alert("Texto 1");
  }
  else{
    document.getElementById("btnTrocar").innerHTML = "Imagem  &#709;";
    alert("Texto 2");
  }
}
<button onclick="trocar()" id="btnTrocar">Imagem &#709;</button>

Within a string does not run the risk of confusion and does not need to use this form of special codes. In fact for this case nowhere would need. Except to run on browsers that do not support reading HTML in certain encodings, but if this is likely to be the least of your problems.

    
06.09.2018 / 16:30