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

157
Views
Javascript solo la primera instancia (no todas) en la página

Estoy tratando de ocultar un elemento de la lista, según el texto dentro de la lista <p> . Lo tengo casi correcto. Sin embargo, mi versión actual no encuentra todas las instancias en una página. Encuentra y oculta la última instancia, pero no las demás. Puede haber 3-4 de estos en una página que me gustaría ocultar.

Ayuda apreciada.

 // select relevant elements var elements = $('p'); // go through the elements and find the one with the value elements.each(function(index, domElement) { var $element = $(domElement); // does the element have the text we're looking for? if ($element.text() === "Happy New Year (Southern)") { $element.parent().hide(); // hide the element with jQuery return false; // jump out of the each } });

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

0

¿Qué hay de usar el filtro primero y luego solo ocultar los elementos después de eso?

 // select relevant elements var elements = $('p'); // go through the elements and find the one with the value elements.filter(function(index) { return $(this).text() === "Happy New Year (Southern)"; }).eq(0).parent().hide();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li> <p>Happy New Year (Northern)</p> </li> <li> <p>Happy New Year (Eastern)</p> </li> <li> <p>Happy New Year (Southern)</p> </li> <li> <p>Happy New Year (Southern)</p> </li> <li> <p>Happy New Year (Southern)</p> </li> <li> <p>Happy New Year (Western)</p> </li> </ul>

Usando .eq(0) seleccionamos solo el "primer" elemento coincidente y luego ocultamos el padre.

Para ocultarlos todos, simplemente omitimos el .eq(0) .

about 4 years ago · Juan Pablo Isaza Report

0

Tal vez esto ayude:

 var elements = document.getElementsByTagName("p"); var searchText = "Happy New Year (Southern)"; for (var i = 0; i < elements.length; i++) { if (elements.textContent == searchText) { elements[i].parent().hide() } }
about 4 years ago · Juan Pablo Isaza Report

0

La solución fue eliminar el return false; como dijo Barmar en los comentarios ( 1 , 2 ):

return false finaliza la iteración .each()

Solo deshazte de return false; y los ocultará a todos.

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!