Get the attribute of several div's and send one at a time to another function

1

I'm trying to get 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]);
  }
};
    
asked by anonymous 15.06.2018 / 20:02

3 answers

4

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

For id , you can only use 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>
    
15.06.2018 / 21:01
2
function deletarTudo() {
  var lista = document.getElementsByTagName("div");
  for (var i = 0; i < lista.length; i++) {
    controle("adicionar", lista[i].getAttribute("id"));
  }
};

maybe this will work

    
15.06.2018 / 20:37
1

As already mentioned, document.querySelectorAll("#lista div") returns a list, type array and you can not get 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>
    
15.06.2018 / 22:36