Home > OS >  native JavaScript - remove html tag but leave contents in same place
native JavaScript - remove html tag but leave contents in same place

Time:02-04

Some sample html:

<section>
   <span >
      this is content before a <a href="#">link</a> and after it.  I really don't need span.unnecessary and and to remove it
   </span>
</section>

Is there a way in vanilla JavaScript to simply remove the <span > using DOM methods?

CodePudding user response:

if you want to select by class only

var unnecessaries = document.getElementsByClassName('unnecessary')

//start LOOP for each unnecessary element
    unnecessaries[0].outerHTML = unnecessaries[0].innerHTML
//end LOOP

if you want to select by combination of span and class

var unnecessaries = document.querySelectorAll('span.unnecessary')

//start LOOP for each unnecessary element
    unnecessaries[0].outerHTML = unnecessaries[0].innerHTML
//end LOOP

CodePudding user response:

Please try this

  var b = document.getElementsByTagName('span');

  while(b.length) {
  var parent = b[ 0 ].parentNode;
  while( b[ 0 ].firstChild ) {
    parent.insertBefore(  b[ 0 ].firstChild, b[ 0 ] );
  }
   parent.removeChild( b[ 0 ] );
  }

The resulting html

   <section>this is content before a <a href="#">link</a> and after it.  I really 
   don't 
  need span.unnecessary and and to remove it

  </section>
  •  Tags:  
  • Related