Khalifa Sabt
Khalifa Sabt

Reputation: 83

Find specific string in a div and delete its html element

is there a way using javascript to find a specific string and delete its' html element. For example, I have this following html code:

<div class="summary">
List of texts:
  <ul>
   <li>Text 0</li>
   <li>Text 1</li>
   <li>Text 2</li>
   <li>Text 3</li> 
   <li>Text 4</li>
   <li>Text 5</li>
  </ul>
</div>

and I want to hide "Text 2", first I want to find this string and then hide it. what I've tried is using html().replace but it hides only the text not the element. JSFiddle

Upvotes: 3

Views: 1956

Answers (4)

Pomme De Terre
Pomme De Terre

Reputation: 372

using JQuery you can do it like that :

$('.summary ul').children().each(function () {
    if($(this).text() == searchedValue) {
        $(this).hide(); 
    }
})

Upvotes: 0

GUISSOUMA Issam
GUISSOUMA Issam

Reputation: 2582

Iterrate over li elements, check if the text content is the searched value, then hide or remove the element.

 $(function() {
  $('.summary li').each(function() {
   var $this = $(this);
   if($this.text() === 'Text 2'){$this.hide();}
  });

});

Upvotes: 1

grgdne
grgdne

Reputation: 239

Your fiddle is pretty close. Here's an updated version removing the element from the DOM.

$('.summary li').each(function() {
   var $this = $(this);
   if ($this.text() === 'Text 2') {
       $this.remove();
   }
});

http://jsfiddle.net/sLa3dkdd/3/

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77482

In jQuery there is :contains

$('.summary li:contains(Text 2)').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="summary">
List of texts:
  <ul>
   <li>Text 0</li>
   <li>Text 1</li>
   <li>Text 2</li>
   <li>Text 3</li> 
   <li>Text 4</li>
   <li>Text 5</li>
  </ul>
</div>

Upvotes: 7

Related Questions