Take the variable div’s attribute and send one at a time to another function

Asked

Viewed 33 times

1

I’m trying to take the attribute of each div and send one at a time, but it’s giving error, the code I tried to do and this:

function deletarTudo() {
  var lista = document.querySelectorAll("#lista div").getAttribute("id");
  for (var i = 0; i < lista.length; i++) {
    controle("adicionar", lista[i]);
  }
};

3 answers

4


Are you using the wrong .getAttribute("id"). The querySelectorAll will generate a list of nodes, so you should take the attribute of each node individually in the loop for.

In the case of id, you can use only lista[i].id instead of .getAttribute("id"):

function deletarTudo() {
  var lista = document.querySelectorAll("#lista div");
  for (var i = 0; i < lista.length; i++) {
    controle("adicionar", lista[i].id);
  }
}


function controle(x,y){
   console.log(x,y)
}

deletarTudo();
<div id="lista">
   <div id="id1">div1</div>
   <div id="id2">div2</div>
   <div id="id3">div3</div>
</div>

2

function deletarTudo() {
  var lista = document.getElementsByTagName("div");
  for (var i = 0; i < lista.length; i++) {
    controle("adicionar", lista[i].getAttribute("id"));
  }
};

maybe it works that way

1

As has already been mentioned document.querySelectorAll("#lista div") returns a list, type array and you cannot fetch the Ids directly, you have to iterate. So you could do with less code the following:

function deletarTudo() {
  var lista = document.querySelectorAll("#lista div");
  lista.forEach(el => controle("adicionar", el.id));
};

Example:

const controle = (metodo, id) => console.log(metodo, id); // só para o exemplo

function deletarTudo() {
  var lista = document.querySelectorAll("#lista div");
  lista.forEach(el => controle("adicionar", el.id));
};


deletarTudo();
<div id="lista">
  <div id="1">1</div>
  <div id="2">2</div>
  <div id="3">3</div>
</div>

Browser other questions tagged

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