Mehdi Raza
Mehdi Raza

Reputation: 9

Why does this function always return "true1"

This is a bit of a modified version of an example in the book 'Eloquent JavaScript'. Need to understand why it always returns "true1". The idea was to find a certain text in the DOM but somehow even if I give a text that does not exist in the html still get "true1" on console.

Please Help

My HTML File:

<!DOCTYPE html>

 <html> 
    <head>      
        <meta charset="UTF-8" />        
        <title> My first JS page</title>
        <script src="script1.js"></script>
    </head> 
    <body>      

        <h1>My first page</h1>
        <p> Hello , I am Mehdi and this is my first page</p>
        <p> And this is the second paragraph on this page and</p>
    </body>
 <script>console.log(talksAbout(document.body, "Tester123"));</script>
</html>

My Javascript File

function talksAbout(node, string){

    if(node.nodeType == document.ELEMENT_NODE){

        for(var i=0; i<node.childNodes.length; i++){

            if(talksAbout(node.childNodes[i], string))
                return "true1";
        }
        return "false1";
    }else if(node.nodeType == document.TEXT_NODE){

        return node.nodeValue.indexOf(string) > -1;
    }


}

Upvotes: 0

Views: 103

Answers (2)

Scott Sauyet
Scott Sauyet

Reputation: 50787

Pointy's answer describes one of the two key problems. The other is that your search string actually is in the document!

You include the script tag with the search string as part of the document. It will get checked as well as you walk the DOM, and so even after you fix the boolean values, you will still return true as long as you have lines like this in the document:

<script>console.log(talksAbout(document.body, "Tester123"));</script>
                                               ^^^^^^^^^  

You could simply run a test from a web developers' console to see this running without such an issue.

Upvotes: 3

Pointy
Pointy

Reputation: 413682

Your function uses the return value of the talksAbout() function as if it were a boolean value. However, the function may return a boolean or it may return one of those two string values, "true1" or "false1". Both of those will appear to be true when used in a boolean context like that if statement around the recursive call.

Upvotes: 9

Related Questions