Bosh
Bosh

Reputation: 1247

JS/Jquery/RegEx - Remove all tags except the ones with classname XYZ

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!

Upvotes: 1

Views: 1147

Answers (2)

user372551
user372551

Reputation:

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();
       }
    });
});

Upvotes: 0

Bosh
Bosh

Reputation: 1247

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);
                });

Upvotes: 1

Related Questions