How to remove elements using jQuery and leave their children intact

jQuery - remove elements leaving their children intact

Removing elements using jQuery is quite easy, but what happens when the elements we need to remove have children and we need to keep them intact? moreover, what happens when the elements we want to remove using jQuery are a list of elements with children to be kept? It’s easy too!

Following the image above, if we wanted to remove the a elements, leaving the img elements, all we need to do is to place this code inside your document.ready call

[js]
jQuery(‘.container’).children().map(function (index) {
jQuery(this).replaceWith(jQuery(this).contents());
});
[/js]

The call searches for all children of .container and runs the map function on them. Map is one of my favourite functions. It’s sort of a filter that you can apply to any given element. In this case, map will be applied to all the a elements inside .container because we used the children function, which only collects the first level children. Then, any mapped element will be replaced by its contents. We could use children again, just wanted to show another function. Contents, unlike children, will also collect any text nodes, so it will be perfect if you are already in a leaf node and want to remove it while keeping the text.

11 thoughts on “How to remove elements using jQuery and leave their children intact”

    1. Of course it is, using unwrap involves one call. The downside is that jQuery 1.4 is quite recent. Even the internal bundled jQuery in WordPress 2.9 is 1.3.2. Some large sites make extensive use of jQuery versions prior to 1.3. If you can use 1.4 go ahead and use unwrap.

Leave a Reply