Jash
Jash

Reputation: 962

How to count list items in HTML by using javascript for IE 7

I am trying to run a javascript which will return me the list (li) items count inside a div. I have tried with various script, but nothing works fine in IE 7.

HTML -

<ul class="ABC">
    <li>1</li>
    <li>2</li>
</ul>

Javascript - document.querySelectorAll('ul.ABC li').length. This should return 2, but in IE 7 it does not work.

I know that query selector is not supported in IE7, i am looking for simple script which can do this. Does any one knows how i can achieve in IE 7 ?

Thanks!

Upvotes: 0

Views: 177

Answers (2)

Spudley
Spudley

Reputation: 168655

As you said you already know, querySelectorAll is not supported in IE7.

If you can't (or don't want to) work around it by using IDs or some other simpler way to select the relevent elements, then you'll need to use a polyfill.

You might want to try this polyfill script which claims to implement querySelectorAll, among other features, for old IE versions.

Alternatively, there's always the ubiquitous jQuery. Simply include jQuery and replace your querySelector code with $('ul.ABC li'), job done.

jQuery's historical reason for existing was to simplify cross-browser stuff like this. If you need to support IE7, there are plenty of good reasons to use jQuery.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

It's easier if you can assign an ID to the list:

<ul id="mylist">

Then you can just do this:

document.getElementById('mylist').children.length;

If this is not an option for you, something more advanced and complex is needed:

function searchTagsForClass(tagName,className) {
    var tags = document.getElementsByTagBame(tagName), l = tags.length, i,
        match = new RegExp("\\b"+className+"\\b","i");
    for( i=0; i<l; i++) {
        if( tags[i].className.match(match)) return tags[i];
    }
}
searchTagsForClass("ul","ABC").children.length;

Upvotes: 1

Related Questions