问题
I have a div like this:
<div id="x" name="x" class="x" style=""></div>
and contained within 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>
etc.
QUESTION 1: How do I detect how many of these divs (class="y") are contained within the container div (class="x")? - (just an alert("") with the number, for example).
QUESTION 2: How do I do something to each of these y-divs (class="y") such as a function that might place the letter "Y" into all of the y-divs using $('.y').html("Y"); , for example??
Any help appreciated guys....
回答1:
You need to find the elements within the ancestor 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 the API:
- descendant selector
- length property
回答2:
alert($('.x .y').length);
$('.x .y').html('Y');
回答3:
//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');
});
回答4:
Try this.
alert($('.x .y').length)
http://api.jquery.com/length/
回答5:
1. The length()
method gets the total amount of returned elements:
alert($('.x .y').length());
2. You were correct in how to set the content on all of the returned elements:
$('.x .y').html('Y');
来源:https://stackoverflow.com/questions/6243554/jquery-how-do-i-detect-how-many-divs-of-a-given-class-exist-within-a-given-div