Remove an Element from an HTML String with jQuery
While working on a project for work today, I encountered a problem that I apparently have never encountered before. What I thought was a very simple function call in jQuery turned out to be a bit more complicated. I needed to removed an HTML element from a string representation of an HTML snippet. jQuery doesn’t quite behave the way I expected and I had trouble finding a solution.
Attempt #1 (Incorrect)
var theString = “<p>A string <span>with a span in it</span></p>”;
var theResult = $(“span”, theString).remove().html();
// Returns: ‘with a span in it’
The code above will return the element I want to remove, not the original string with the element removed. Not quite what I want.
Attempt #2 (Incorrect)
var theString = “<p>A string <span>with a span in it</span></p>”;
var theResult = $(“span”, theString).remove().end().html();
// Returns: ‘A string’
The code above, at least, gets the reference right, but unfortunatley, jQuery returns the ‘inner’ HTML but what I need is the ‘outer’ HTML. For some reason, it strips the enclosing element and gives me back jut the contents of the element.
Attempt #3 (Incorrect)
var theString = “<p>A string <span>with a span in it</span></p>”;
var theResult = $(“span”, theString).remove().end()[0];
// Returns: (Object) [HTMLParagraphElement]
The code above, gives me back the correct result but as the wrong type. This code returns an HTMLParagraphElement object. I can easily append this return value to another element or the document body, but I started with a string and I want to get a string back.
The Solution
I ended up using a little bit of jQuery slight-of-hand to get the result I want. The second incorrect approach above actually does return what I want, but when I call the jQuery.html() method, it returns the innerHTML.
So my approach is to first append the element to a new (temporary) DIV, then call jQuery.html() on the DIV and so get back the full HTML string I started with, minus the element I removed.
;(function($) {
$.strRemove = function(theTarget, theString) {
return $(“<div/>”).append(
$(theTarget, theString).remove().end()
).html();
};
})(jQuery);
Now I can get exactly the result I expect with the code below.
var theString = “<p>A string <span>with a span in it</span></p>”;
var theResult = $.strRemove(“span”, theString);
// Returns: “<p>A string </p>”