Finding an Element by Tag Name

I’m on page 70 of Simply Javascript. The topic is on Finding an Element by Tag Name. My question concerns this code:

var listItems = document.getElementsByTagName(“li”);

While reading through the instructions, I can understand that executing the code will search througgh all of the descendants of the document node with a tag name of “li” and assign that group to the listItems variable, which will contain a node list. I wrote the code onto my js file, which is referenced to an HTML file. After running the Javascript through my HTML file, my mind tells me that I’m supposed to see a node list? And where is this node list supposed to be located?

Hi wils_v, welcome to the forums,

All that single line does is assign the DOM’s li elements to the variable. If you want to do something with the data (parse, alter, display, whatever), you need more lines of code. The data is in memory.

I imagine the book has something in mind and will get to it shortly. But if you’re anxious to see something right away you could try a simple

var listItems = document.getElementsByTagName("li");
alert(listItems);

Thanks for your reply.

As you may have noticed, I’m such a novice to JS and consider myself a very visual learner. So from your response, unless we write another alert line to disclose the “nodelist”, we won’t see this nodelist, right?

I went back to my work and wrote down that line you gave and it only popped out an alert with an exclamation mark inside a yellow rectangle beside the word object inside a bracket - as in [object]. Not sure what i’m expected to see after declaring that second command in my js file.

Since you spoke of the book having something in mind, I read further and found that the book was trying to output the tagname of each of the nodes by using a “for” loop. The full codes are displayed as:

var listItems = document.getElementsByTagName(“li”);

for (var i = 0; i < listItems.length; i++)
{
alert(listItems[i].nodeName);
}

Given that there’s an alert command, what am I expected to see?

You should get an alert for each of the list items - (hopefully there aren’t too many) - when you close one the next will open. Next to the alert icon - the ! triangle - you will see the nodeName of each item.

I might suggest then that you take a look at a book called Head First JavaScript.

It is very visual in its learning techniques and might be just the thing for you to learn from.

Thanks very much for the explanation. I will try link the JS file to another HTML file with a lot of <li> elements then. I suppose I should get that results you described.

Thanks, you’re very helpful!

Thanks for this. I’m more of a visual learner so I think this might be useful.