Using jquery to calculate the total number of images in a <id>
I have one div and inside it I have some images like <img src= etc
I want to calculate the total number of images in this div. Also I want to store these image IDs in mysql using PHP ...
thank
To count them, you can do this:
alert($('#myDiv img').length);
To grab all ids into an array, you can do something like this:
var ids = [];
$('#myDiv img').each(function() {
ids.push($(this).attr('id'));
});
or using $.map
, as suggested by @Russ Cam:
var idsArr = $.map($('#myDiv img'), function(n,i) {
return n.id;
});
and all this will give you a score, using an length
array (if all images have an id).
It might be convenient to send them to the server as a comma separated string like:
var idsStr = ids.join(',');
$('div > div > img').length
will get the number of elements <img>
that are immediate children <div>
that are immediate children of the elements <div>
. You will need some way to uniquely identify the div with the images you want, either by id (recommended), class name, or DOM position .