Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove DOM element if it contains a string

So I have this code where it checks if the Name exists and if it does it deletes the span tag it's nested in.

<div id="box">
  <br>
  <span style="font-size: 12px">
    <a>
      <span style="color: #000000">
        <b>Name</b>
      </span>
    </a>
  </span>

However name can be also placed in these tags:

  <br>
  <span>
    <a>Name</a>
  </span>
</div>

How would I use jquery to check it? I've tried:

$('span:contains("Name")').remove();
$('span > a > span b:contains("Name")').remove();

Nothing seems to work.

Edit#2: Also there are br tags I just included them. I'd like to remove them only if they're before the removed tags.

Thanks.

like image 884
Gui Thomas Avatar asked Oct 29 '25 15:10

Gui Thomas


1 Answers

You can use filter() if you want to target exactly element with text "Name", not as :contains which will target element with text e.g "Name with some other text...":

Set code inside .load() callback function

$('#box').load('myUri', function () {
    $('#box span').has('b, a').filter(function () {
        return $.trim($(this).text()) === "Name";
    }).remove();
});

Equivalent to :contains would be:

$('#box span').has('b, a').filter(function(){
    return $(this).text().indexOf("Name") != -1;
}).remove();

UPDATED FOLLOWING COMMENT:

$('#box').load('myUri', function () {
     $('#box span').has('b, a').filter(function () {
         var toRemoveSpan = $(this).text().indexOf("Name") != -1 ? true : false;
         if (toRemoveSpan && $('span').prev('br').length) {
             $(this).prev('br').remove()
         }
         return toRemoveSpan;
     }).remove();
 });

This will give the same than just: $('#box').empty();

If this is not behaviour you want, you have to be more specific in your question.

like image 176
A. Wolff Avatar answered Oct 31 '25 05:10

A. Wolff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!