Home > Software design >  Javascript only first one (not all) instances on page
Javascript only first one (not all) instances on page

Time:01-04

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
    }
});

CodePudding user response:

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).

CodePudding user response:

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()
    }
}

CodePudding user response:

As commented removing the return false; has solved this. Thanks!

  •  Tags:  
  • Related