Paul L
Paul L

Reputation: 213

How do you replace an HTML tag with another tag in jquery?

I have a site I'm working on and it uses 'aside' tags, which I'm not getting IE8 to be able to read no matter what I try, even with an HTML5 Shiv. So, I'm wondering, how would you replace existing tags with other tags with jQuery?

For example, if I wanted to change

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

to

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

How would that be done?

Upvotes: 10

Views: 34800

Answers (5)

zaphodb
zaphodb

Reputation: 505

Here's a solution that replaces HTML5 block tags, preserving the styling on the divs that replace the HTML5 tags. Simply replacing tags leaves the 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));
    });

(may need a little more work on the source tag, which has "src" and "type" attributes)

Upvotes: 1

palaѕн
palaѕн

Reputation: 73906

Try this:

$('aside').contents().unwrap().wrap('<div/>');
  • Get the contents of aside first.
  • Now unwrap the contents.
  • Now simply, wrap the contents inside a new tag, here a div.

DEMO


Also, you can do this using .replaceWith() method like:

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

DEMO

Upvotes: 33

gtmsingh
gtmsingh

Reputation: 106

This works for every element in the document and it preserves the contents. Using wraps leads to occurrences of many div elements if there are line breaks in the contents of the aside element.

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

Upvotes: 3

alokrajiv
alokrajiv

Reputation: 1186

This will do the job:

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

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

Upvotes: 1

Memolition
Memolition

Reputation: 494

$('aside').replaceWith('<div><h3></h3></div>');

Upvotes: 6

Related Questions