Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
Alternar clase y eliminar de otros elementos usando un filtro

Me gustaría alternar entre clases en una página con dos secciones: cuando haces clic en la primera, alterna una clase llamada open y la elimina de la otra sección que finalmente la tenía.

Me las arreglé para hacer que las cosas funcionen con el conmutador, pero la otra section no tiene la clase open eliminada. Así que comencé a experimentar con el .filter no logro entenderlo...

El comportamiento: solo un div debe estar rojo al mismo tiempo

 document.addEventListener("DOMContentLoaded", function(e) {
const sections = document.getElementsByTagName("section");

Array.from(sections).forEach(function(section) {
 section.addEventListener('click', function(el) {
 //console.log(sections, el)
 //var diff = sections.filter(element => element !== section)
 //console.log(diff)
 section.classList.toggle("open")
 });
 });
 
});
 body{
 margin: 0;

}

main{
 width: 100%;
 display: flex;
 justify-content: center;
 flex-direction: row; 
}

section{
 transition: all 300ms ease-in-out;
 padding-top: 2em;
 flex-grow: 2;
 flex-basis: 0;
 display: flex;
flex-direction: column;
}

section:nth-child(1){
 background-color: lightblue;
}

section:nth-child(2){
 background: rgb(137, 110, 148);
}

section.open{
 background: red;

}

img{
 width: 90%;
 align-self: center;
}
 <main>
 <section class="left" id="swup" >
 <img src="https://picsum.photos/200/300" alt="">
 </section>
 <section class="right" id="swup" >
 <img src="https://picsum.photos/200/400" alt="">
</section>

</main>

almost 4 years ago · Santiago Trujillo
2 answers
Answer question

0

En lugar de usar toggle , considere usar add y remove en la lista de clases. Sin necesidad de filter .

 // Cache the sections
const sections = document.querySelectorAll('section');

// Add listeners to them
sections.forEach(section => {
 section.addEventListener('click', handleClick);
});

// Remove the open classes from all the sections first
// and then add one to the section that was clicked
function handleClick() {
 sections.forEach(section => section.classList.remove('open'));
 this.classList.add('open');
}
 main,section{display:flex}body{margin:0}main{width:100%;justify-content:center;flex-direction:row}section{transition:.3s ease-in-out;padding-top:2em;flex-grow:2;flex-basis:0;flex-direction:column}section:first-child{background-color:#add8e6}section:nth-child(2){background:#896e94}section.open{background:red}img{width:90%;align-self:center}
 <main>
 <section class="left" id="swup">
 <img src="https://picsum.photos/200/300" alt="">
 </section>
 <section class="right" id="swup">
 <img src="https://picsum.photos/200/400" alt="">
 </section>
</main>

almost 4 years ago · Santiago Trujillo Report

0

Estaba en el camino correcto con filter() , simplemente olvidó convertir sections a Array primero.

 document.addEventListener("DOMContentLoaded", function(e) {
const sections = document.getElementsByTagName("section");

Array.from(sections).forEach(function(section) {
 section.addEventListener('click', function(el) {
 //console.log(sections, el)
 var diff = Array.from(sections).filter(element => element !== section)
 diff.forEach(function(otherEl) {
 otherEl.classList.remove("open")
 })
 section.classList.toggle("open")
 });
 });
 
});
 body{
 margin: 0;

}

main{
 width: 100%;
 display: flex;
 justify-content: center;
 flex-direction: row; 
}

section{
 transition: all 300ms ease-in-out;
 padding-top: 2em;
 flex-grow: 2;
 flex-basis: 0;
 display: flex;
flex-direction: column;
}

section:nth-child(1){
 background-color: lightblue;
}

section:nth-child(2){
 background: rgb(137, 110, 148);
}

section.open{
 background: red;

}

img{
 width: 90%;
 align-self: center;
}
 <main>
 <section class="left" id="swup" >
 <img src="https://picsum.photos/200/300" alt="">
 </section>
 <section class="right" id="swup" >
 <img src="https://picsum.photos/200/400" alt="">
</section>

</main>

almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!