3

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.

Rob
  • 14,746
  • 28
  • 47
  • 65

2 Answers2

6

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>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Wow, you're quick! Thank you for this answer. In the back of my head I recall having heard heard some bad things about using `contains` and I think that stuck. This was far more simple than I had realised. I'll tick your answer when it allows me :) –  Nov 23 '16 at 12:45
1

You could do it by combining :has and :contains selector,

jQuery("li:has(label:contains('Hide'))").hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li><label>Show</label></li>
<li><label>Hide</label></li>
<li><label>Hide</label></li>
<li><label>Show</label></li>
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130