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

181
Visualizações
Attaching an index of one array to the index of another array

The idea I'm trying to do is, let's say I have some DOM elements and I want to create a function that accepts 2 arrays, one for the elements and another for the class names. How I make sure that element at index 0 for example only has the class name I pass at index 0 of the other array.

Here is a visual of what I'm trying to do

function addClassName(arrOfElements, arrOfClassNames) {
  // Here is what ive tested
  arrOfElements.forEach((el) => {
    el.classList.add(arrOfClassNames);
  });
}

Expected Result

addClassName([el1, el2], ["class-for-el1", "class-for-el2"]

console.log(el1.classList);
// Result: "class-for-el1"

console.log(el2.classList);
// Result: "class-for-el2"
<div class="class-for-el1"></div>
<div class="class-for-el2"></div>

What i get instead

console.log(el1.classList);
// Result: "class-for-el1", "class-for-el2"

console.log(el2.classList);
// Result: "class-for-el2", "class-for-el2"
<div class="class-for-el1 class-for-el2"></div>
<div class="class-for-el1 class-for-el2"></div>

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

0

If number of items of arrOfElements and arrOfClassNames is the same, you can do smthing like:

function addClassName(arrOfElements, arrOfClassNames) {
  // Here is what ive tested
  arrOfElements.forEach((el, index) => {
    el.classList.add(arrOfClassNames[index]);
  });
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Array.prototype.forEach() callback gives you two parameters, first one being the element itself and second one being its index, you can use this property to achieve what you wanted like this

const el1 = document.getElementById('1'),
    el2 = document.getElementById('2');

function addClassName(arrOfElements, arrOfClassNames) {
    arrOfElements.forEach((el, index) => {
        el.classList.add(arrOfClassNames[index]);
    });
}

addClassName([el1, el2], ['test', 'test1']);

console.log(`class for el1 - ${el1.className}\n`);
console.log(`class for el2 - ${el2.className}`);
<div id="1"></div>
<div id="2"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

You can simply use array index to get the class name and add it

el.classList.add(arrOfClassNames[i]);

Note: There are 3 arguments that are passed to the callback function

1) element: The current element being processed in the array.

2) index (Optional): The index of element in the array.

3) array (Optional): The array forEach() was called upon.

function addClassName(arrOfElements, arrOfClassNames) {
  // Here is what ive tested
  arrOfElements.forEach((el, i) => {
    el.classList.add(arrOfClassNames[i]);
  });
}

const [el1, el2] = document.querySelectorAll("div");
addClassName([el1, el2], ["class-for-el1", "class-for-el2"]);

console.log(el1.classList);
// Result: "class-for-el1"

console.log(el2.classList);
// Result: "class-for-el2"
<div>First</div>
<div> second </div>

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