jQuery remove tag from HTML String without RegEx

You can wrap your string in a jQuery object and do some sort of a manipulation like this:

var removeElements = function(text, selector) {
    var wrapped = $("<div>" + text + "</div>");
    wrapped.find(selector).remove();
    return wrapped.html();
}

USAGE

var removedSpanString = removeElements("<span>Some Text</span> Some other Text", "span");

The beauty of this approach is that you can specify a jquery selector which to remove. i.e. you may wish to remove the <th> in a string. This would be very handy in that case.
Hope this helps!

Leave a Comment