user1555863
user1555863

Reputation: 2607

Javascript innerText nuance

I'm wondering about the innerText property. Consider the following markup:

HTML

<div class="myClass">
    <div>
         <div>foo</div>
   </div>
</div>
<div class="myClass">
    <div>
         <div>bar</div>
    </div>
</div>

Then, lets run the following code:

JS

var a = document.querySelectorAll('div.myClass');
//var a = document.querySelectorAll('div.myClass div div');
for (var i=0; i<a.length; i++){
    console.log(a[i].innerText);
    if (a[i].innerText == "foo"){
        console.log("found");
    }
}

FIDDLE HERE

Running this code as is, outputs foo, and empty line, and then bar.

If I comment out the first line of the script, and uncomment the second one which then closes-in on the exact level of the divs containing the text, this code outputs foo, found, bar.

My question here is: If on the first iteration the script outputs foo, how come a[i].innerText == "foo" isn't true? Oh, and where is that empty line comming from?

Upvotes: 1

Views: 227

Answers (2)

wildhaber
wildhaber

Reputation: 1661

As an alternative to Halil Bilgin's answer you can trim the inner text to remove the \n

In this example I've used jQuery.trim():

for (var i=0; i<a.length; i++){
    console.log(a[i].innerText);
    if (jQuery.trim(a[i].innerText) == "foo"){
        $("pre").text("found:"+a[i].innerText);
        console.log("found");
    }
}

http://jsfiddle.net/82L9g868/2/

Upvotes: 0

Halil Bilgin
Halil Bilgin

Reputation: 513

Since myClass has 2 div inside of itself, javascript see them as a line "\n" and hence "foo" doesn't equal "foo\n"

But if we change the code like that:

 if (a[i].innerText == "foo\n"){
        console.log("found");
 }

Then you can see found log in the console. http://jsfiddle.net/3149ha75/5/

Upvotes: 3

Related Questions