I want to show three elements of the list however it only shows the first

Good night!
I am studying the book Only JS Javascript (sitepoint).
In Chapter 3, I’m working with DOM’s.

window.onload = function ()
    var listItems = document.getElementsByTagName("li");

    for (var i = 0; i < listItems.length; i++)

It only takes the first element of the list in case Paragraph.

Because the loop is not being done? I want the alert to show me also the other two, unordered list, and list items.

        Há três tipos de elementos neste corpo:

        <li>lista não ordenada</li>
        <li>item de lista</li>

Thanks a lot

Hi RenataFaria, welcome to the forums.

Please tell me that isn’t the exact code the book has. Does your alert show

for listItems[0].childNodes[0].nodeValue = “parágrafo”
for listItems[1].childNodes[1].nodeValue = null or undefined
for listItems[2].childNodes[2].nodeValue = null or undefined

See the problem?

Hi Mittineague, thanks for your response.

The code is a bit different from the book, I modified it for the purpose of training.

In fact, I want to learn as given a content any, in case a list with several options, as I do reading from item to item in this list.


In the example HTML you posted, though the li elements don’t show it, they each have a “text node” inside them. Hence the use of childNodes
Your loop is incrementing the variable i but each li has only one text (child) node.

If you know the HTML will always be this way, you could change i to 0, or you could try using textContent instead of childNode.nodeValue

Perfect response. It worked very well.

window.onload = function () {;
var listItems = document.getElementsByTagName(“li”);
var qtdItens = listItems.length;

for (var i = 0; i &lt; qtdItens; i++)