How to replace HTML tag with another tag in jquery?

I have a website I'm working on and it uses β€œaside” tags that I don't get so that IE8 can read no matter what I try, even with HTML5 Shiv. So, I am wondering, how would you replace existing tags with other tags in jQuery?

For example, if I wanted to change

<aside> <h3></h3> </aside> 

to

 <div> <h3></h3> </div> 

How to do it?

+6
source share
5 answers

Try the following:

 $('aside').contents().unwrap().wrap('<div/>'); 
  • First enter the contents of aside .
  • Now unwrap contents.
  • Now just wrap contents inside the new tag, here is the div .

Demo


Alternatively, you can do this with the .replaceWith() method, for example:

 $('aside').replaceWith(function () { return $('<div/>', { html: $(this).html() }); }); 

Demo

+26
source
 $('aside').replaceWith('<div><h3></h3></div>'); 
+7
source

This works for every element of the document and saves the content. Using wrappers results in many div elements appearing if there are line breaks in the contents of the aside element.

$('aside').each(function() { $(this).replaceWith("<div>"+$(this).html()+"</div>") });

+3
source

This will complete the task:

  $('aside').replaceWith( "<div>" + $('aside').html() + "</div>" ); 

Also using .html () gives a more dynamic approach.

+1
source

Here's a solution that replaces HTML5 block tags while keeping the style in divs replacing HTML5 tags. Simple tag substitution leaves attributes behind.

 $('article, aside, figcaption, figure, footer, header, nav, section, source') .each(function(){ var el = $(this), html = el.html(), attrs = { "id": el.attr('id'), "classes": el.attr('class'), "styles": el.attr('style') }; console.log('Replacing ' + el.prop('tagName') + ', classes: ' + attrs.classes); el.replaceWith($('<div></div>').html(html).attr(attrs)); }); 

(it may take a little more work with the original tag, which has the attributes "src" and "type")

0
source

Source: https://habr.com/ru/post/943901/


All Articles