Comparison going wrong

Asked

Viewed 83 times

1

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

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

Apparently, when it comes to taking the value he is "converting" the &#709; and can’t 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 there is such a "conversion":

  • what her reason is?
  • why it does not treat as a "normal text"?
  • has some way to get this text from the button without changing anything?

1 answer

0


what her reason is?

Because this is a way of writing in code, because it is difficult to write otherwise immobilely in a current way. But it’s just like it’s in the code, in the document it’s not like that, it’s the character itself. Like HTML is one thing, like string is another.

why it does not treat as a "normal text"?

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

has some way to get this text from the button without changing anything?

Of course not, if something is wrong 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>

I put in the Github for future reference.

Within a string does not run the risk of confusion and does not need to use this form of special codes. Actually for this case nowhere would need. Except to run in browsers that don’t support reading HTML in certain encodings, but if this happens it’s probably the least of your problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.