-1

Here's my problem. The code below is a simplified version to point out the weird error.

<html>
    <head>
    <script type = "text/javascript">
    window.onload = function test()
    {
    body = document.getElementsByTagName('body')[0];
    div = document.createElement('div');
    div.id = 'div';
                body.appendChild(div);
                document.getElementById('div').innerHTML = "text";
                if(document.getElementById('div').childNodes[0] == "text")
                    {
                        alert('true');
                    }else {
                        alert('false');
                    }
                }
</script>
<style>
</style>
</head>
<body>
</body>

Why is it false!? Its virtually the SAME EXACT string. Is it the .innerHTML part? Any answer relevant to this issue would help. It's late at night and I'm angry and confused.

4
  • There could be some spaces issue! Commented Apr 1, 2014 at 4:21
  • childNodes[0].textContent? Commented Apr 1, 2014 at 4:22
  • try childNodes[0].data or value Commented Apr 1, 2014 at 4:22
  • Exact duplicate of why innerHTML does not return true when compared with same string value? Commented Apr 1, 2014 at 4:27

1 Answer 1

2

You can compare the nodeValue of your child node instead since childNodes return an object:

if (document.getElementById('div').childNodes[0].nodeValue == "text")
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, just wondering though, what exactly causes the problem above?
childNodes return an object. You cannot compare object with a string literal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.