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

198
Views
Seleccione el último elemento que no está vacío (innerText! == "") de una clase con querySelector

Intento seleccionar el último elemento que no está vacío de una clase.

Por ejemplo, aquí me gustaría seleccionar el segundo elemento:

 <span class="test">A</span> <span class="test">B</span> <span class="test"></span> <span class="test"></span>

Pero debido a que el texto interno cambia (con las acciones del usuario), no puedo simplemente usar

 document.querySelector(".test:nth-of-type(2)");

He intentado esto pero no funciona:

 document.querySelector('.test:not(:empty):nth-last-of-type(1)'); 

 function myFunction(){ document.querySelector('.test:not(:empty):nth-last-of-type(1)').innerText = "test"; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="test">A</span><br> <span class="test">B</span><br> <span class="test"></span><br> <span class="test"></span><br> <input type="button" value="change 2nd element" onclick="myFunction()"/>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

¿Por qué usar querySelector para esto? Yo sugeriría esto:

 document .querySelectorAll('.test') // all with test class .filter(elem => elem.innerText !== '') // only not empty .at(-1) // last element // or, if you need backward browser compatibility: document .querySelectorAll('.test') // all with test class .filter(elem => elem.innerText !== '') // only not empty .reverse()[0]
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!