Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
If both divs have same class add another class to both divs

How can I add a class to 2 divs that have same class?

In this example I have 3 div and 2 of them share the class ".matched".

How can I add in JS another class (for example .sameclass) to these 2 divs?

Many many thanks in advance!

<div class="container">
  <div class="box1 matched"></div>
  <div class="box2 matched"></div>
  <div class="box3"></div>
</div>

CSS

.container {
  display: flex;
}

.box1 {
  width: 100px;
  height: 100px;
  background-color: red;
}

.box2 {
  width: 100px;
  height: 100px;
  background: green;
}

.box3 {
  width: 100px;
  height: 100px;
  background: purple;
}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Search for the elements with querySelectorAll and then use element.classList.add("matched") within a loop to add the classes.

about 4 years ago · Juan Pablo Isaza Denunciar

0

  1. You have to get a reference to the DIVs you want to add a CSS class to. In your case those elements have the shared CSS class matched. JavaScript offers a nifty method to get all elements of a particular class called getElementsByClassName().

let divs=document.getElementsByClassName("matched");

This returns a HTMLcollection - basically an array - of all the elements with a CSS class matched.

  1. Now loop over the elements stored in the HTMLCollection obtained from step 1 and add a specific class using the .classList.add() method. e.g.

myElement.classList.add("anotherClass");

All together we have:

let divs = document.getElementsByClassName("matched");

for (let a = 0; a < divs.length; a++) {
  divs[a].classList.add("anotherClass");
}
.anotherClass {
  color: red;
}
<div class="container">
  <div class="box1 matched">a</div>
  <div class="box2 matched">b</div>
  <div class="box3">c</div>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can write somthing like this:

let elements = document.getElementsByClassName("matched");
for(let element of elements) {
    element.classList.add("same");
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda