Posted 30 days ago. Visible to the public.

jQuery: How to replace DOM nodes with their contents

You know that you can use jQuery's text() to get an element's contents without any tags.
If you want to remove only some tags, but keep others, use contents() and unwrap(). Here is how.

Consider the following example element.

Copy
$container = $('<div><strong>Hello</strong> <em>World</em></div>')

Let's say we want to discard any <em> tags, but keep their contents.
Simply find them, then dive into their child nodes via contents, and use unwrap replace their parents (the found ems) with the children.

Copy
$container.find('em').contents().unwrap()

Note that this modifies the elements inside $container directly. When you look at the DOM now, the <em> will be gone, but its contents will be kept.

Copy
$container.html() // returns "<strong>Hello</strong> World"

Also note that contents() includes text and comment nodes which is essential for this approach to work. jQuery usually won't reveal such nodes to you.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Author of this card:

Avatar
Arne Hartherz
Last edit:
23 days ago
by Arne Hartherz
Keywords:
unpack
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev