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?
The size() method returns the number of elements matched by the jQuery selector.
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.
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()
You can simply use the jQuery . length property to find the number of elements in a DIV element or any other element.
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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With