-1

What is the best javascript solution to change a span to a div but keep its contents and the span's own classes. The classes are set so this can be hard coded.

<span class="my class">
  <p class="content">
   DYNAMIC CONTENT HERE
  </p>
</span>

I want to use js to change this into

<div class="my class">
  <p class="content">
   DYNAMIC CONTENT HERE
  </p>
</div>

Using replaceWith() seems to fail on IE as it is not supported.

Thanks.

knox-flaneur
  • 149
  • 1
  • 13
  • 2
    Why not just use CSS to make the span act like a div? – epascarello Dec 28 '17 at 00:21
  • Why do you think `replaceWith` doesn't work with IE? And - be specific - which version of IE do you need to support? 8? 9? 10? 11? Edge? – random_user_name Dec 28 '17 at 00:28
  • @andrewwhitaker had a great answer for this here: https://stackoverflow.com/questions/8584098. They also include how to use it as a plugin so you can just call `$('.my.class').changeElementType('div');` – Mark Dec 28 '17 at 00:31
  • Possible duplicate of [how to change an element type using jquery](https://stackoverflow.com/questions/8584098/how-to-change-an-element-type-using-jquery) – random_user_name Dec 28 '17 at 02:30

1 Answers1

1

This is an example to do it with plain javascript:

var span = document.querySelector('.my.class'),
    div = document.createElement('div');

div.setAttribute('class', span.getAttribute('class'));
div.innerHTML = span.innerHTML;
span.parentNode.insertBefore(div, span);
span.parentNode.removeChild(span);

Accoding to caniuse.com, both .insertBefore() and .removeChild(), together with the get and set attribute methods are supported by IE too.

Please note, that this does not deal with event handlers or other javascript objects that were attached to nodes within the original <span>.

dferenc
  • 7,163
  • 12
  • 36
  • 42