JQuery - how to determine how many divs of a given class exist in a given div?

I have a div like:

<div id="x" name="x" class="x" style=""></div>

and contained in this div, I have several divs like this:

<div id="y_1" name="y_1" class="y" style=""></div>
<div id="y_2" name="y_2" class="y" style=""></div>
<div id="y_3" name="y_3" class="y" style=""></div>

and etc.

QUESTION 1: How to determine how many of these divs (class = "y") are contained in the div container (class = "x")? - (for example, only a warning ("") with a number.)

QUESTION 2: How can I do something for each of these y-divs (class = "y"), such as a function that can put the letter "Y" in all y-divs using $ ('. Y') . Html ("Y") ;, for example,

Any help appreciated by the guys ....

+3
source share
5 answers

You need to find the elements inside the parent element.

$('#x div.y').length; // number of class y elements under element x
$('#x div.y').html('Y'); // run a jQuery method on the y elements

See API:

+6
alert($('.x .y').length);

$('.x .y').html('Y');
+4

//instead of $('#x .y') you can also use $('#x').find('.y')
alert($('#x .y').length())

$('#x .y').each(function(){
    //do what you want to $(this)
    $(this).html('Y');
});
+2

.

alert($('.x .y').length)

http://api.jquery.com/length/

+2

1. length() :

alert($('.x .y').length());

2 .. You correctly specified how to set the content for all returned items:

$('.x .y').html('Y');

+1
source

All Articles