Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
how to check if indexOf is even or odd?

I want to add a style to odd and even elements of this array.

 let myArr = ["a", "b", "c", "d", "e", "f"];
const btn = document.querySelector("#btn");
const body1 = document.body;

let i = 0;

btn.addEventListener("click", function () {
  i++;
  let newDiv = document.createElement("div");
  newDiv.textContent = myArr[i];
  body1.appendChild(newDiv);
});

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Simplest and most efficient way of determining if a number is even or odd:

number & 1
about 4 years ago · Juan Pablo Isaza Relatório

0

You will need to loop through the array to get the index. Using that, you can do the modulus check to see if it's even or odd and do something with the div before pushing it on to the body.

document.addEventListener('DOMContentLoaded', () => {
  let myArr = ["a", "b", "c", "d", "e", "f"];
  const btn = document.querySelector("#btn");
  const body1 = document.body;

  // Start at 1 to avoid any + 1 in the modulus check
  for(let i = 1; i <= myArr.length; i++) {
    const newDiv = document.createElement("div");
    newDiv.style.width = '100px'
    newDiv.style.height = '100px'
    newDiv.style.margin = '5px'
    newDiv.style.color = 'white'
    // - 1 because we start the loop at 1 and indexes start at 0 in JS
    newDiv.textContent = myArr[i - 1]; 

    if (i % 2 === 0) {
      newDiv.style.backgroundColor = 'red'
      newDiv.style.float = 'right'
    } else {
      newDiv.style.backgroundColor = 'blue'
      newDiv.style.float = 'left'
    }
    body1.appendChild(newDiv);
  }
})

about 4 years ago · Juan Pablo Isaza Relatório

0

I assume the items in the array are DOM elements? So you maybe want to do something like this:

arr.forEach((item, index) => {
 if (index % 2 == 0) {
   // Even
   item.style = ...;
   // or maybe
   item.className = ...;
 } else {
   // Same here, apply whatever style/class you want to use for the odd elements.
      }
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda