azamsharp
azamsharp

Reputation: 20086

How to check for {} value in JavaScript?

For some reason in the code below the currentRow.cells returns {}. How can I check for that? I do not want to execute lines if the currentRow.cells returns {}.

 currentRow = document.createElement("TR");
 if(currentRow.cells.length > 0) { .. do something }

UPDATE 1:

All I want is to check for empty object. if the currentRow.cells is an empty object then do nothing.

Upvotes: 0

Views: 3340

Answers (5)

shingokko
shingokko

Reputation: 412

cells property isn't available in <tr> on IE8 and below. A workout is to use childNodes as suggested above. The following code checks if cells is undefined:

var currentRow = document.createElement("TR");
if (typeof currentRow.cells === "undefined") {
    // use currentRow.childNodes
}
else {
    // use currentRow.cells
}

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227270

currentRow is a <tr> (or a HTMLTableRowElement), and currentRow.cells is a HTMLCollection (not an Array ([]) or an object ({})).

If currentRow.cells is undefined, that means that current row isn't a <tr>, it's another element.

To check if a DOM element is empty, you can use childNodes (this will never be undefined).

if(currentRow.childNodes.length === 0){
    // empty
}
else{
    // not empty
}

Edit: Better yet, you can use hasChildNodes.

if(!currentRow.hasChildNodes()){
    // empty
}
else{
    // not empty
}

Upvotes: 0

Jordan
Jordan

Reputation: 32532

I always get an object of type HTMLCollection.

You should be able to then check the length of the collection using code like this:

if(currentRow.cells.length != 0) {
    //row and cells exist, work with them
}

Upvotes: 2

stewe
stewe

Reputation: 42642

To answer your question in the title:

function is_empty(obj) {
    for(var i in obj) {
        if(obj.hasOwnProperty(i))
            return false;
    }
    return true;
}

alert(is_empty({})); // true

Upvotes: 0

Jason
Jason

Reputation: 52523

jQuery has a helper method called $.isEmptyObject().

Their code for this is simple:

function isEmptyObject( obj ) {
    for ( var name in obj ) {
        return false;
    }
    return true;
}

If you don't want to use the whole jQuery library, you can snag this method and drop it somewhere in your own code base!

Upvotes: 1

Related Questions