Why is if not comparing to html < entity?

Asked

Viewed 52 times

2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <span>&lt;</span>
    
    <script>
        let text = document.querySelector("span");
        
        text.addEventListener("click", function(){
            if (text.textContent == "&lt;")
            {
                alert("é igual")
            }
            
            else
            {
                alert("não é igual")
            }
        });
    </script>
</body>
</html>

The above example I am trying to compare if two values are equal in the case &lt; is equal to &lt; in case I had to return true, but it’s returning to me false, why?

2 answers

7

Basically because you are confusing the content of the element with the HTML representation.

The textual content (textContent) of span is < and not &lt; (is what you used in the code), so the correct comparison is:

text.textContent == "<"

If only I’d used innerHTML, then yes this comparison would work:

text.innerHTML == "&lt;"

See working:

var text = document.querySelector("span");
console.log( 'Texto é igual &lt;? : ' + (text.textContent == "&lt;") );
console.log( 'Texto é igual < ? : ' + (text.textContent == "<") );
console.log( 'HTML é igual &lt;? : ' + (text.innerHTML == "&lt;") );
console.log( 'HTML é igual < ? : ' + (text.innerHTML == "<") );
<span>&lt;</span>

2

The actual representation of this line

<span>&lt;</span>

is "<" and so you should make the comparison this way:

text.textContent == "<"

Browser other questions tagged

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