Devesh Agrawal
Devesh Agrawal

Reputation: 9212

jquery compare returning false instead of true

while reading label from HTML page using $(this).text and comparing it with a same string, its returning false.

var readText = $(this).text(); // assume $(this).text() reads 1234 for you
readText === "1234" //this return false

Why this behavior? Also how to fix this so compare will return true.

Upvotes: 1

Views: 470

Answers (2)

Jonan
Jonan

Reputation: 2536

It's because 1234 is an integer, and "1234" is a string. If you use the === operator, you check if they both have the same value + the same type. If you just want to check if they have the same value, use ==.
More information about JavaScript comparison operators: http://www.w3schools.com/js/js_comparisons.asp

If $(this).text() is a string, you should do $(this).text().trim. This will remove whitespace and newlines, which could lead to the comparison returning false

Upvotes: 4

OptimusCrime
OptimusCrime

Reputation: 14863

Not sure if you are correct about this.

This simple fiddle claims otherwise: http://jsfiddle.net/e7nKP/1/

The js is like this:

$(function () {
    var readText = $('#foo').text();
    console.log(readText === "1234");
});

Where #foo is a simple div with 1234 as content.

Upvotes: 0

Related Questions