Lyner Kharl
Lyner Kharl

Reputation: 125

jquery text() compare to string

How to compare strings to jquery text()? I've tried this one but it will not work.

var str = 'hello';
var string = $(this).find("text").trim();

if(str == string)
{          
   string.css("visibility", "visible");
}

What's wrong with my code? Any idea please? thank you

Upvotes: 2

Views: 39876

Answers (3)

danikaze
danikaze

Reputation: 1654

Aren't you getting any error?

Usually calling .find on something will search for a DOM element. find is not for searching text.

With find("text") you are looking for elements in the DOM tree. And they don't have .trim() methods associated, so you should be getting an error like 'TypeError: undefined is not a function'

Maybe what you want to do is the following...

var string_elem = $(this),
    str = 'hello',
    string = string_elem.find("text").text().trim();

if(str === string) {
    string_elem.css('visibility', 'visible');
}

Also, if you want your string comparison to be case insensitive you should do something like this

if(str.toLowerCase() === string.toLowerCase()) 

Upvotes: 1

Guffa
Guffa

Reputation: 700242

If you want to use the text method you need to actually use it. Using find("text") would try fo find a <text> element inside the element, and there are no such elements.

Also, use the jQuery trim method as the string.trim method isn't available in all browsers. Apply the style to the element, not the string:

var str = 'hello';
var string = $.trim($(this).text());

if(str == string)
{          
   $(this).css("visibility", "visible");
}

Upvotes: 8

doniyor
doniyor

Reputation: 37856

string is just a string, so you cannot .css();.

and better use some other variable name instead of string, this seems to be already reserved one.

try this

var str = 'hello';
var string = $(this).find("text").trim();
var string_elem = $(this);
if(str == string){          
   string_elem.css("visibility", "visible");
}   

Upvotes: 0

Related Questions