Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get size of jQuery object

I'm saving key-value pairs in div container by using:

$( '#div_id').data( key, value);

At the end I need to check if anything is stored in this div container.

So first I get the content by calling:

var data = $( '#div_id').data();

Then to check its size with data.length or data.size.

But both functions don't exists. As I know the data function in jquery returns an object, so I should be able to get the size of this object.

How do I get the size of the object returned by the data function in jquery?

like image 444
NovumCoder Avatar asked Dec 03 '10 14:12

NovumCoder


People also ask

What does size () method of jQuery returns?

The size() method returns the number of elements matched by the jQuery selector.

How do you find the length of a object?

Method 1: Using the Object. keys() method is used to return the object property name as an array. The length property is used to get the number of keys present in the object. It gives the length of the object.

What is jQuery size?

The size() is an inbuilt method in jQuery used to find the number of elements matched by the given selector. This method is removed in jQuery 3.0 instead of this length() has been introduced. Syntax: $(selector).size()

How do you find the length of a div?

You can simply use the jQuery . length property to find the number of elements in a DIV element or any other element.


2 Answers

Objects do not have a "size". You could count its properties, though:

function getPropertyCount(obj) {
    var count = 0,
        key;

    for (key in obj) {
        if (obj.hasOwnProperty(key)) {
            count++;
        }
    }

    return count;
}

Usage:

alert(getPropertyCount(data));
like image 196
jwueller Avatar answered Sep 28 '22 23:09

jwueller


It's not the best idea to store those key/value pairs at this level on the object/node.

var data = $( '#div_id').data();

returns all data that is attached to this node, this would include event handlers for instance of there are any.

So the best solution is to create an object which contains all of your data:

$('#div_id').data('mydata', {});
/* ... */
$('#div_id').data('mydata')[key] = value;

To your actual question. Plain Javascript objects do not own a .length property. You have to check that for yourself, looping over the keys:

var mylen = 0;
for(var prop in $('#div_id').data('mydata')) {
    mylen++;  
}

This should be improved by also checking and calling the .hasOwnProperty() method which makes sure that the current property is not inheritated from somewhere in the prototype chain.

like image 36
jAndy Avatar answered Sep 29 '22 00:09

jAndy