How to get all <ul> elements using Document.querySelectorAll() - Javascript

Asked

Viewed 57 times

2

  • I want to get these li within the ul using Document.querySelectorAll()

inserir a descrição da imagem aqui

I tried that way, but Nodelist didn’t come from li , only appeared to ul

    function TrocaLataPrincipal(){
    let pepsiPrincipal = document.querySelector(".pepsi")
    let lataPepsi = document.querySelectorAll(".latasDeRefri")
    console.log(lataPepsi)
}

TrocaLataPrincipal()
  • Console output

inserir a descrição da imagem aqui

2 answers

2

You are only getting the UL, so you need to select the LI within the UL:

function TrocaLataPrincipal(){
    const pepsiPrincipal = document.querySelector(".pepsi")
    const lataPepsi = document.querySelectorAll(".latasDeRefri li")
    console.log(lataPepsi)
}

TrocaLataPrincipal()

2


When you search for .latasDeRefri, is bringing only the element that has the class "latasDeRefri", which in this case is the ul.

If you want all the li inside it, just include this in the selector:

let latasPepsi = document.querySelectorAll(".latasDeRefri li");
//                                                   aqui ^^
for (const li of latasPepsi)
    console.log(li);
<ul class="latasDeRefri">
  <li>pepsi 1</li>
  <li>pepsi 2</li>
  <li>pepsi 3</li>
</ul>

Another alternative is to search for li from the ul:

// busca o primeiro ul com a classe latasDeRefri
let ul = document.querySelector(".latasDeRefri");
// busca os "li" dentro do ul
for (const li of ul.querySelectorAll('li'))
    console.log(li);
<ul class="latasDeRefri">
  <li>pepsi 1</li>
  <li>pepsi 2</li>
  <li>pepsi 3</li>
</ul>

<ul>
  <li>outro</li>
</ul>

Note that I have now searched for "li" from ul found (and not from the document). So he only seeks what’s inside the ul (if I searched the document, he would also find the <li>outro</li>).


Read to documentation for more information on selectors.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.