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

317
Views
Iterar a través de js for loop de manera similar a nth-child (#n + #)

Pregunta bastante sencilla; Soy un poco nuevo en JS y me sorprendió no poder encontrar algo en mis búsquedas.

Dentro de estos dos bucles for, estoy recorriendo vistas previas de artículos en una tienda de Woocommerce. Wordpress agrega automáticamente las clases "primera" y "última" aquí para ajustar los márgenes para el estilo. Tengo un poco de truco aquí donde estoy usando ventas adicionales como una sección manual de productos recomendados.

Como verá a continuación, primero estoy tratando de eliminar todas las instancias de esas clases en cada li, luego agregar las "últimas" clases solo a algunas lis: aquellas que funcionan dentro de las columnas / ubicación que configuré. Estoy tratando de hacer esto dentro de una declaración si/entonces que verifica el ancho de la pantalla. No estaba teniendo suerte al utilizar dos bucles for separados dentro de cada declaración, por razones que actualmente están un poco por encima de mi cabeza.

Lo que me gustaría hacer: me gustaría automatizar el ciclo for para pasar automáticamente por cada dos (o cada 3 en la instrucción else) elementos en mi variable upsellLi. Con CSS podrías hacer algo como .upsell .li:nth-child(1n + 2);. He intentado aumentar las ventas de Li ([1] + 2); aquí, pero no tuve suerte.

¡Muchas gracias por echar un vistazo!

 function columnChange(mobile) { if (mobile.matches) { // If media query matches variable below function //If screen size matches variable (is smaller than 1000px wide in our case), change upsell products to have 2 columns upsellCols.classList.remove('columns-3'); upsellCols.classList.add('columns-2'); //After that, reset first and last columns, then add .last class to 2nd and 4th items to adjust spacing. This assumes a maximum of two rows. for (var i = 0; i < upsellLi.length; i++ ) { upsellLi[i].classList.remove('first'); upsellLi[i].classList.remove('last'); upsellLi[1].classList.add('last'); upsellLi[3].classList.add('last'); upsellLi[5].classList.add('last'); //repeat with 5, 7, etc within brackets to add support for more rows } } else { //If screen size is larger than 1000px, change upsell products to have 3 columns upsellCols.classList.remove('columns-2'); upsellCols.classList.add('columns-3'); //After that, reset first and last columns, then add .last class to 3rd and 6th items to adjust spacing. This assumes a maximum of two rows. The "i is already defined" error in Elementor is actually chill because we're only using one for loop at a time thanks to the if/then statement :) for (var i = 0; i < upsellLi.length; i++ ) { upsellLi[i].classList.remove('first'); upsellLi[i].classList.remove('last'); upsellLi[2].classList.add('last'); upsellLi[5].classList.add('last'); //repeat with 8, 11, etc within brackets to add support for more rows } } }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

¡Responda por @CBroe en los comentarios! Aquí es donde terminé para hacer que esto funcione:

 function columnChange(mobile) { if (mobile.matches) { // If media query matches variable below function //If screen size matches variable (is smaller than 1000px wide in our case), change upsell products to have 2 columns upsellCols.classList.remove('columns-3'); upsellCols.classList.add('columns-2'); //After that, reset first and last columns, then add .last class to last product in each row for (var i = 0; i < upsellLi.length; i++ ) { upsellLi[i].classList.remove('first'); upsellLi[i].classList.remove('last'); //Add "last" class to every two instances of upsellLi - check if each iteration's number within the loop is divisible by 2. The 1 at the end offsets the count to start on the second iteration (since the count starts at 0) if(i % 2 === 1) { upsellLi[i].classList.add('last'); } } } else { //If screen size is larger than 1000px, change upsell products to have 3 columns upsellCols.classList.remove('columns-2'); upsellCols.classList.add('columns-3'); //After that, reset first and last columns, then add .last class to last product in each row for (var i = 0; i < upsellLi.length; i++ ) { upsellLi[i].classList.remove('first'); upsellLi[i].classList.remove('last'); //Add "last" class to every 3 instances of upsellLi - check if each iteration's number within the loop is divisible by 3. The 2 at the end offsets the count to start on the third iteration (since the count starts at 0) if(i % 3 === 2) { upsellLi[i].classList.add('last'); } } } }
about 4 years ago · Juan Pablo Isaza 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!