Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.find() returns an object even when there's no matching child element in the DOM

I am trying to find an element with the ID '' that is within the element '', and therefore is its child.

I am using the $.find method to perform the search.

If the child object is found, I'd like to perform some actions, and if the child object isn't found, I'd like to do different things.

However, even though I know that there is no such child element existing, the jQuery.find method reports an object that I am not sure, from inspecting in the Watches window, what it is.

Here's the relevant code snippet:

function CreateResourceKeyTextBox(resourceKeyId, editMode) {
    var resourceKeyTableCell = $("#tdKeyResourceKeyId" + resourceKeyId);

    var resourceKeyNameTextBox = null;

    var alreadyExistingResourceKeyNameTextBox = resourceKeyTableCell.find('#txtResourceKeyName' + resourceKeyId);

    if (alreadyExistingResourceKeyNameTextBox != null && typeof alreadyExistingResourceKeyNameTextBox != "undefined") {
        resourceKeyTableCell.html('');
        resourceKeyNameTextBox = alreadyExistingResourceKeyNameTextBox;
        resourceKeyNameTextBox.css('display', 'block');
        resourceKeyNameTextBox.appendTo('#tdKeyResourceKeyId' + resourceKeyId);
        resourceKeyNameTextBox.css('width', '96%');
    }
like image 226
Water Cooler v2 Avatar asked Oct 07 '13 11:10

Water Cooler v2


People also ask

Does find return jQuery object?

find() returns an object even when there's no matching child element in the DOM.

What does $() return in jQuery?

$() does not return the jQuery function, (which is $ itself,) but returns a wrapped set, with all those helpful methods on it.

How check selector is empty in jQuery?

This method can be used on this element to test if it is empty by using “:empty” selector. The “:empty” selector is used to select all the elements that have no children. It will return true if the element is empty, otherwise, return false.

How do you iterate through an object in jQuery?

The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.


1 Answers

jQuery query functions always return an object, even if there's no matching DOM elements.

Check the length, it will be 0 if there's no element in the set :

if (alreadyExistingResourceKeyNameTextBox.length ...
like image 74
Denys Séguret Avatar answered Sep 22 '22 13:09

Denys Séguret