Sudarshan Kalebere Sudarshan Kalebere - 3 months ago 7
Javascript Question

How can I find specific string in li>div and hide it

I have a ul list which has li's and in li there is div with no class and id. I just want to find li>div which has text saying 'Certificats et forfaits' and hide anchor tag which is next to it. Is it possible?

Here is my code

<ul class="select2-choices">

<li class="select2-search-choice">
<div>Informatique Électronique</div>
<a href="#" class="select2-search-choice-close" tabindex="-1"></a>
</li>

<li class="select2-search-choice">
<div>Informatique Électronique &gt; Accessoires Informatique</div>
<a href="#" class="select2-search-choice-close" tabindex="-1"></a>
</li>

<li class="select2-search-choice">
<div>Mode et Accessoires</div>
<a href="#" class="select2-search-choice-close" tabindex="-1"></a>
</li>

<li class="select2-search-choice">
<div>Certificats et forfaits</div>
<a href="#" class="select2-search-choice-close" tabindex="-1"></a>
</li>

<li class="select2-search-field">
<label for="s2id_autogen3" class="select2-offscreen"></label>
<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input" id="s2id_autogen3" placeholder="" style="width: 20px;">
</li>

</ul>


In my above list I want to find text Certificats et forfaits which is in div always and it will be always after li, once I find that I need to hide anchor tag next to it. How can I achieve this any help?

Answer

Please check below snippet.

$( document ).ready(function() {
  $('ul li').each(function(){
    if($(this).children('div').text() == 'Certificats et forfaits'){
      $(this).children('a').hide();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="select2-choices">  

<li class="select2-search-choice">    
<div>Informatique Électronique</div>    
<a href="#" class="select2-search-choice-close" tabindex="-1"></a>
</li>

<li class="select2-search-choice">   
<div>Informatique Électronique &gt; Accessoires Informatique</div>
<a href="#" class="select2-search-choice-close" tabindex="-1"></a>
</li>

<li class="select2-search-choice">    
<div>Mode et Accessoires</div>    
<a href="#" class="select2-search-choice-close" tabindex="-1"></a>
</li>

<li class="select2-search-choice">    
<div>Certificats et forfaits</div>    
<a href="#" class="select2-search-choice-close" tabindex="-1"></a>
</li>

<li class="select2-search-field">    
<label for="s2id_autogen3" class="select2-offscreen"></label>    
<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input" id="s2id_autogen3" placeholder="" style="width: 20px;">  
</li>

</ul>