Read more

jQuery: How to replace DOM nodes with their contents

Arne Hartherz
April 25, 2018Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Consider the following example element.

$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 Show archive.org snapshot , and use unwrap Show archive.org snapshot replace their parents (the found ems) with the children.

$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.

$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.

Posted by Arne Hartherz to makandra dev (2018-04-25 08:55)