matt136 matt136 - 14 days ago 8
HTML Question

Loop Through and Hide Elements Containing a String

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.

Answer

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>