tags:

views:

58

answers:

2

i have one DIV and inside div i have some imaes for example <img src= etc

i want to calculate total Number of Images in that DIV also i want to save these images ID into mysql using PHP...

Thanks

A: 
$('div > div > img').length

will get the number of <img> elements that are immediate children of <div> elements that are immediate children of <div> elements. You will need some way to uniquely identify the div with the images that you require, either through id (recommended), class name or DOM position.

Russ Cam
+1  A: 

To count them, you can do this:

alert($('#myDiv img').length);

To grab all the ids into an array, you can do something like this:

var ids = [];
$('#myDiv img').each(function() {
    ids.push($(this).attr('id'));
});

or by using a $.map, as per @Russ Cam's suggestion:

var idsArr = $.map($('#myDiv img'), function(n,i) { 
                  return n.id; 
             });

and those will give you the count anyway, by the length of the array (provided all images have an ID).

It might be convenient to send them to the server as a comma-separated string, e.g.:

var idsStr = ids.join(',');
karim79
how about using $.map ? For example, $.map($('#myDiv img'), function(n,i) { return n.id; });
Russ Cam
@Russ Cam - this is true, I've not used maps much, I'm going to steal that idea and put it into the answer, after upvoting your comment.
karim79
@karim79- with so much selector power and jQuery object property functions, I often find myself overlooking the utility functions, even though they are really useful :)
Russ Cam
@Russ Cam - I know, it's ridiculous the number of things I've been doing the hard/old-school way only to be stunned when I come across things like this.
karim79