Looping through LI elements in UL

How would I get the height of every list-item inside a ul if I used getElementsByTagName(‘ul’)? In my mind, getElementsByTagName(‘ul’) would return an array containing every list-item, but instead, it seems to return “an object” (whatever that means) and when I try to use alert(typeof(ul)) inside a for statement on it, it returns a bunch of stuff that isn’t even close to what I originally thought would be in there…

Edit: I also wanted to mention, too, that when I use getElementById on the ul, I get everything I thought I needed to, but using getElementsByTagName (even if it’s only being used on one ul) returns stuff I didn’t anticipate. What’s up with that?

Any insight into this is appreciated.

getElementsByTagName() returns a NodeList, which can be used similar to an array, i.e., with bracket notation. Each element in the NodeList will represent a <ul> element.

If you want to access the list items, rather than the list, you should use getElementsByTagName("li").

For instance, if you have markup like this,

<ul id="foo">

you can access the list items this way,

var ul = document.getElementById("foo");
var items = ul.getElementsByTagName("li");
for (var i = 0; i < items.length; ++i) {
  // do something with items[i], which is a <li> element

One more thing(s) Tommy :):

1.) Is the use of double-quotation marks necessary when passing an argument or is using single-quotation marks acceptable? Both seem to work, but is one frowned upon over another?

2.) Would this be an acceptable way to measure the height of a list (UL)?

3.) How might one apply this to multiple lists? There is no native “getElementsByClass”, but since doing it by “getElementsByTagName” is wrong, what other options would there be?

They are equivalent, and it’s only a matter of taste. Die-hard PHP programmers tend to prefer single quotes. As an old C/C++/Java developer I use double quotes out of habit, since single quotes mean something else in those languages.

If you want the height in pixels of the rendered box, then you could access that information in a couple of different ways. One might be the .offsetHeight property (I’m not 100% sure how cross-browser compatible that is). Another would be to access the computed style for the element, but that’s rather messy to get to work cross-browser.

Do it in multiple steps. First use document.getElementsByTagName("ul") to get a list of all unordered lists. Then iterate through that list (optionally filtering per class) and use getElementsByTagName("li") per list. Something like this,

var lists = document.getElementsByTagName("ul");
for (var i = 0; i < lists.length; ++i) {
    // filter so that only lists with the class "foo" are counted
    if (/(^|\\s)foo(\\s|$)/.test(lists[i].className)) {
        var items = lists[i].getElementsByTagName("li");
        for (var j = 0; j < items.length; ++j) {
            // do something with items[j]