Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Remove a tag without deleting content

I am wondering if it is possible to remove a tag but leave the content in tact? For example, is it possible to remove the SPAN tag but leave SPAN's content there?

<p>The weather is sure <span>sunny</span> today</p> //original

<p>The weather is sure sunny today</p> //turn it into this

I have tried using this method of using replaceWith(), but it it turned the HTML into

<p>
  "The weather is sure " 
  "sunny"
  " today"
</p>

EDIT : After testing all of your answers, I realized that my code is at fault. The reason why I keep getting three split text nodes is due to the insertion of the SPAN tag. I'll create another question to try to fix my problem.

like image 919
Jon Avatar asked Mar 24 '12 01:03

Jon


People also ask

How do you close a tag in JavaScript?

Also to close an any element tag you must put the slash in front of the elements name. </script>, </html> etc.

What does .remove do in JavaScript?

The remove() method removes an element (or node) from the document.

How do I remove an innerHTML element?

innerHTML property innerHTML property will get or set the HTML markup contained within the element. But you can utilize this property to “remove” any elements within the container, by setting the value to an empty string. This property is fully cross-browser, read full docs on innerHTML.


2 Answers

<p>The weather is sure <span>sunny</span> today</p>;


var span=document.getElementsByTagName('span')[0]; // get the span
var pa=span.parentNode;
while(span.firstChild) pa.insertBefore(span.firstChild, span);

pa.removeChild(span);
like image 51
kennebec Avatar answered Sep 20 '22 17:09

kennebec


jQuery has easier ways:

var spans = $('span');
spans.contents().unwrap();

With different selector methods, it is possible to remove deeply nested spans or just direct children spans of an element.

like image 24
user1106995 Avatar answered Sep 16 '22 17:09

user1106995