user6373207
user6373207

Reputation:

How to remove div with a particular text in it

I have some div tags which has some text & elements in it & I want to remove those div's, They are looks like this

<div style="font-family:verdana;font-size:12px;">
    Example
    <a href="http://www.example.com" title="hey">example</a>
</div>

There are many div's like this & I want to remove them all with using jQuery or javascript

Upvotes: 3

Views: 2293

Answers (2)

Juan Ferreras
Juan Ferreras

Reputation: 2861

Based on Darren's answer, if you want to be extra sure (as :contains will match and delete any div containing the word example), you can make sure it's a div that has an anchor with that same example as children, then go back to the parent and remove it.

If this doesn't work, please paste a few more divs so we can see a common pattern and target it the safest way possible.

$(document).ready(function(){
  
  $('#remove').click(function(e){

  $("div:contains('Example')").children("a:contains('example')").parent("div:contains('Example')").remove()
})
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="font-family:verdana;font-size:12px;">Example<a href="http://www.example.com" title="hey"> example</a></div>
<div style="font-family:verdana;font-size:12px;">Don't remove<a href="http://www.example.com" title="hey"> example</a></div>
<div style="font-family:verdana;font-size:12px;">Example<a href="http://www.example.com" title="hey"> don't remove</a></div>

<button id="remove">
Remove undesired divs
</button>

Upvotes: 0

Darren
Darren

Reputation: 70728

If the elements have nothing in common such as a class, you can remove it by using the :contains and remove() method.

$("div:contains('Example')").remove()

Full example shown below:

$("div:contains('Example')").remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


<div>
  Example
</div>
<div>
  Darren
</div>

If the elements do have something in common you could use the class selector.

$(".common-class").remove();

Upvotes: 4

Related Questions