Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop Through and Hide Elements Containing a String [duplicate]

I apologise for my ignorance - I'm very new to programming.

I'm attempting to create a script which will loop through label elements and then hide the parent li element if the label text contains a specific string. Please see my code below:

var labelclass = jQuery("li label");

for (i = 0; i < labelclass.length; i++) {
  if ((labelclass).text().indexOf("Hide") >= 0) {
    jQuery(this).closest("li").css("display", "none");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><label>Show</label></li>
  <li><label>Hide</label></li>
  <li><label>Hide</label></li>
  <li><label>Show</label></li>
</ul>

I don't know how far off I am here, but I think I could possibly be mis-using this. The loop could also be incorrect. Could anybody please provide any insight so that I know where to go next with this? Thank you very much for your time.


1 Answers

You don't need a loop here, you can simply use the :contains selector with parent() to get the li, then hide() it. Try this:

$("li label:contains('Hide')").parent().hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><label>Show</label></li>
  <li><label>Hide</label></li>
  <li><label>Hide</label></li>
  <li><label>Show</label></li>
</ul>

The caveat with this is that :contains will match any portion of the content, so 'Do Not Hide' would be hidden too. To get an exact match you could instead use filter():

$("li label").filter(function() {
  return $(this).text().trim() == 'Hide';
}).parent().hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><label>Show</label></li>
  <li><label>Hide</label></li>
  <li><label>Do Not Hide</label></li>
  <li><label>Show</label></li>
</ul>
like image 119
Rory McCrossan Avatar answered Aug 17 '26 04:08

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!