views:

68

answers:

2

Hi everybody,
this is driving me nuts ;-) I have a string whith various span tags... I want to remove all span tags except the ones with classname XYZ... The problem is that i havent found a solution to leave the closing tag...

My starting point is this regex:

 text = text.replace(/<\/?[^>]+(>|$)/g, "");

But everything i tried to say "DONT DO IT IF MATCH classnameXYZ Failed till now...

Any ideas? Thank you in advance!

A: 

Ok, this works for my needs ;-)

                $('#text > span').each(function(intIndex){
                    var word;
                    if ($(this).hasClass('checked')) {
                        word = "<span>"+$(this).html()+"</span>";
                    } else {
                        word = $(this).html();
                        word = word.replace(/<\/?[^>]+(>|$)/g, "");
                    }
                    console.log(word);
                });
Bosh
+1  A: 

This can be done with out a regular expression, more over your answer need to cache the entire html, which would be slow, try the below code, It may help :)

$(function()
    $('#text > span').each(function() {
       if(!$(this).hasClass('XYZ')) { 
           $(this).remove();
       }
    });
});
Ninja Dude
Hmm, as far as i understand this removes the whole element...
Bosh
In your question `Remove all tags except the ones with classname XYZ` what do u mean by Remove all tags ?? Doesn't it refer to remove entire element ?
Ninja Dude