Comparing Attributes of a List with Javascript

Asked

Viewed 732 times

2

Hello, I have an array with li, I need to compare the values of the attributes, all need to be equal. example..

I have 2 li inside a ul

<li onclick="controle.selecionarVolta(this)" data-id="3" data-name="Rotina 3" data-criar="0" data-leitura="0" data-alterar="0" data-deletar="0" data-visitante="0" style="background: none;">Rotina 3</li>

<li onclick="controle.selecionarVolta(this)" data-id="3" data-name="Rotina 3" data-criar="0" data-leitura="0" data-alterar="0" data-deletar="0" data-visitante="1" style="background: none;">Rotina 2</li>

I need to check that all date values are equal to the two...

date-name, date-create, date-change, date-delete and date-visitor..

All must contain the same value, if they have the same value me returns true;

I’m getting these read this way..

var lista = document.querySelector('.rotinas_selecionadas').getElementsByTagName('li')

then I need to go through this list, and check if all the dates I said above are equal...

Thank you for your ja ;D

Sorry, I put that it was an array, actually are objects

1 answer

0


The idea here is:

  • Store all values of lis in an array
  • Check if the first attribute of the first item is equal to the second
  • The criterion is that the attributes are in the same position, otherwise the comparison will go wrong

var lista = document.querySelectorAll('.rotinas_selecionadas')[0].getElementsByTagName('li');
var itens = [], igual = false;

for (let i = 0; i < lista.length; i++) {
  itens.push(lista[i].getAttribute("data-name"));
  itens.push(lista[i].getAttribute("data-criar"));
  itens.push(lista[i].getAttribute("data-alterar"));
  itens.push(lista[i].getAttribute("data-deletar"));
  itens.push(lista[i].getAttribute("data-visitante"));
}
for (let i = 0; i < itens.length - 5; i++) {
  if (itens[i] == itens[i+5]) igual = true;
  else igual = false;
}
console.log("É igual: " + igual);
<ul class="rotinas_selecionadas">
  <li onclick="controle.selecionarVolta(this)" data-id="3" data-name="Rotina 3" data-criar="0" data-leitura="0" data-alterar="0" data-deletar="0" data-visitante="0" style="background: none;">Rotina 3</li>

  <li onclick="controle.selecionarVolta(this)" data-id="3" data-name="Rotina 3" data-criar="0" data-leitura="0" data-alterar="0" data-deletar="0" data-visitante="1" style="background: none;">Rotina 2</li>
</ul>

Browser other questions tagged

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