jQuery - If UL exists and how many LI
Im looking for a way, in jQuery, to check if a UL exists AND if it does count the number of LI elements are contained within it.
The following jQuery loads a UL into a hidden DIV if there are new records to be fetched from the database:
j(".refreshMe").everyTime(5000,function(i){
j.ajax({
url: "refresh.php?latest="+className+"",
cache: false,
success: function(html){
j(".refreshMe").html(html);
}
})
});
If a UL is returned I want to count how many LI elements are in the list,开发者_Python百科 then write that value to the page.
How can I achieve this in jQuery?
You can do it like this:
j(".refreshMe").everyTime(5000,function(i){
j.ajax({
url: "refresh.php?latest="+className+"",
cache: false,
success: function(html){
alert($("li", html).length); //number of <li> found
j(".refreshMe").html(html);
}
})
});
In your success
handler just use the returned data as the context to look in, so $("li", html)
only looks for <li>
elements in the server response, and .length
is the count found, you can take the value and place it where you want it in the page.
精彩评论