Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery detect if .find(' ').text() is defined or not

I have such a code

if ($('#bar #username').text()!=$('.widget-' + widget.id).find('.user').text())
{
//do something
}

Unfortunately, it doesn't go through if $('.widget-' + widget.id).find('.user').text() does not exist/ underfined.

How to check if it is defined?

I've tried if (typeof $('.widget-' + widget.id).find('.user') === "undefined") to check whether it is defined or not, but it doesn't help because

alert (typeof $('.widget-' + widget.id).find('.user')) shows Object,

alert (typeof $('.widget-' + widget.id).find('.user').text()) shows String.

like image 703
Haradzieniec Avatar asked Dec 03 '22 02:12

Haradzieniec


2 Answers

As per the jQuery FAQ, check the length property:

if ($('.widget-' + widget.id).find('.user').length) {
    // it exists
}
like image 165
Matt Ball Avatar answered Dec 28 '22 07:12

Matt Ball


If you want to see whether a jQuery object matched any DOM elements, use $("whatever").length -- it will be nonzero.

like image 31
Jon Avatar answered Dec 28 '22 08:12

Jon