jQuery detect if .find(' ').text() is defined or not
19,805
Solution 1
As per the jQuery FAQ, check the length
property:
if ($('.widget-' + widget.id).find('.user').length) {
// it exists
}
Solution 2
If you want to see whether a jQuery object matched any DOM elements, use $("whatever").length
-- it will be nonzero.
Author by
Haradzieniec
Updated on June 13, 2022Comments
-
Haradzieniec almost 2 years
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 becausealert (typeof $('.widget-' + widget.id).find('.user'))
showsObject
,alert (typeof $('.widget-' + widget.id).find('.user').text())
showsString
.