How to count elements inside an object?
My ajax request is returning an object with my HTML inside it, I want to count the divs in this object, just can开发者_运维知识库't figure out how.
Some code:
$.ajax({
type: "GET",
url: "/activity_results.html?"+options,
cache: false,
success: function(html, status){
if(html != ""){
$(html).appendTo("#comments");
alert(($(html)).length);
}
}
});
In the alert I am showing the length of the whole HTML object but I want to really be drilling down into it and showing the length of a specific set of divs.
There are two ways to do it:
$("#comments div").length
Or with the context parameter:
$("div", "#comments").length
They'll both give you the number of divs inside comments, but the 2nd method is faster.
If I understand what you're trying to do then it looks like the above solution would work for you. But there is a 3rd possibility. If you've already selected an object and need to see how many elements of a certain type are inside it, then that's a little different. If for example you're working with "this", then it's not practical to use the above method.
Instead you might do something like this:
$(this).find("div").length
Or this to get the count of immediate divs only:
$(this).children("div").length
精彩评论