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

不羁的心 提交于 2019-12-31 14:45:14

问题


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?


回答1:


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




回答2:


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



回答3:


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>") });




回答4:


This will do the job:

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

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




回答5:


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)



来源:https://stackoverflow.com/questions/16285791/how-do-you-replace-an-html-tag-with-another-tag-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!