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

159
Views
Javascript only first one (not all) instances on page

I'm trying to hide a list item, based on the text within the list <p>. I have it almost right. However, my current version doesn't find every instance on a page. It finds, and hides, the last instance, but not the others. There can be 3-4 of these on a page I would like to hide.

Help appreciated.

// 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

What about using filter first, and then only hiding the elements after that?

// 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>

Using .eq(0) we select only the "first" matched item, and then hide the parent.

To hide all of them, we just omit the .eq(0).

about 4 years ago · Juan Pablo Isaza Report

0

Maybe this will help:

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

The solution was to remove the return false; as Barmar said in the comments (1, 2):

return false ends the .each() iteration

Just get rid of return false; and it will hide all of them.

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!