开发者

How to count the number of <li> returned through ajax using Javascript?

I have a ajax code which returns the 开发者_Go百科list items as

<li>one</li>
<li>Two</li>

Each time it will return different number of <li>'s. I want to check the number of <li> it returns. How to check it using JavaScript.


Here ya go:

$(returnedHTML).find('li').length

This takes the returnedHTML and only counts the line items within it.


ajaxHtml.split('<li').length - 1 for counting the raw ajax html.

Or, element.getElementsByTagName("li").length (with element being a parent container for the LI tags.)


Have you tried:

var elements = document.getElementsByTagName('li');
var count = elements.length;


If you need to look within a specific list, jQuery makes it simple:

$("DIV_NAME > ul > li").length


If the list you want to test is coming in as a string from an AJAX request, you'll just treat it like a string, instead of a set of DOM objects.

Take a look at this bit of code.

var input = "<li>one</li><li>Two</li>";
var pattern = /<li>/gi;

var match;
var count = 0;
while(match = pattern.exec(input)) {
    count++;
}

alert("There are "+count+" occurences of <li> in the input string.");

What I'm doing here is using an regular expression to find occurrences of <li> case insensitively (just to be certain) and globally (treat the entire string as a single block of text to be searched).


FIXED: Some people thought that I am counting LIs on link click event and also not counting it from html response. Here is the edited answer.

If you got html response something like this:

myhtml.html:

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

Then your jQuery part may be look like this:

$.get('myhtml.html', function(data) {
   alert( $(data).find("li").length ); // 3
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜