Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

Remove all elements that satisfy a condition

        <div class="myClass1">
            <span>tesutokana</span>
        </div>
        <div class="myClass2">
            <span>tesutoroma</span>
        </div>
        <div class="myClass1">
            <span>-</span>
        </div>
        <div class="myClass2">
            <span>-</span>
        </div>
        <div class="myClass1">
            <span>-</span>
        </div>
        <div class="myClass2">
            <span>-</span>
        </div>

I want to remove all divs that are just <span>-</span> from classes myClass1 and myClass2. Tried with .each() but I can't seem to get the hang of it, mostly with what are the arguments of the function I should call. Any help?

Upvotes: 0

Views: 180

Answers (5)

Jay Harris
Jay Harris

Reputation: 4271

here is a simple solution. fiddle

var doc = document.body;
doc.innerHTML = doc.innerHTML.replace(/<div(\s)+(.)*class="myClass(1|2)"(.)*>(\s|\n|\t)*<span>-<\/span>(\s|\n|\t)*<\/div>/ig,'');

this may be the fastest solution because it's not using a loop or an external library.

or

 var j = document.getElementsByClassName('myClass1');
 var t = document.getElementsByClassName('myClass2');
 var x = t.length--;
 while(x--) {
   t[x].innerHTML = t[x].innerHTML.replace(/(<span>-<\/span>)/g,'');
 }
 x = j.length--;

 while(x--) {
   j[x].innerHTML = j[x].innerHTML.replace(/(<span>-<\/span>)/g,'');
 }

fiddle

Upvotes: 1

Bill Criswell
Bill Criswell

Reputation: 32941

I would use .filter().

$('div').filter(function(){
  var $spans = $(this).find('> span');
  return $spans.length === 1 && $spans.text() === '-';
}).remove();

Here's a quick demo: http://jsfiddle.net/VbpzZ/1/

Upvotes: 0

Alvaro
Alvaro

Reputation: 41605

You can do it by comparing the content of the span in a condition:

$('.myClass1, .myClass2').each(function(){
    var mySpan = $(this).find('span');

    if(mySpan.text() == '-'){
        mySpan.closest('div').remove();    
    }
});

Living example: http://jsfiddle.net/8CNkW/2/

Update:

This one doesn't have the problem with texts containing the - string such as ---, test-test etc.

Plush, is 80% faster than the contains option named in other answers: http://jsperf.com/just-a-demo

Upvotes: 2

Haroldo_OK
Haroldo_OK

Reputation: 7280

You could use .filter() to do the filtering.

Just like that:

$('.myClass1,.myClass2').filter(function(i, el){ return el.innerHTML.trim() == '<span>-</span>' }).remove()

Upvotes: 1

c.P.u1
c.P.u1

Reputation: 17094

Use the :contains selector

$("div span:contains(-)").remove();

Remove the whole div:

$("div span:contains(-)").parent().remove();

JSFiddle

Note that this is a quick and dirty solution as it'll remove all spans that contain a -

Upvotes: 2

Related Questions