如何在jquery中用另一个标签替换HTML标签?

9

我正在开发一个网站,其中使用了“aside”标签,但无论我尝试什么方法,包括使用HTML5 Shiv,都无法让IE8识别它们。因此,我想知道,如何使用jQuery将现有的标签替换为其他标签?

例如,如果我想要更改:

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

to

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

那应该怎么做呢?

你试图通过替换标签来实现什么目的? - George Johnston
2
document.createElement('aside') 应该可以让您在 IE8 中使用 aside 标签。您正在使用 html5 doctype,对吗? - Kevin B
重复的问题答案:https://dev59.com/c3E85IYBdhLWcg3wXCO1#9468280 我更喜欢链接的未被选择的答案。 - tomdemuyt
.replaceWith('标签在这里'); - Memolition
啊,我明白发生了什么。IE8 错误地立即关闭了开头的 aside 标签,例如 <aside>foo</aside> 变成了 <aside/>foo</aside/>,因此替换可能会更加困难一些。 - Kevin B
显示剩余2条评论
5个回答

32

试试这个:

$('aside').contents().unwrap().wrap('<div/>');
  • 首先获取aside的内容。
  • 现在进行unwrap操作。
  • 然后简单地将内容包装在一个新标签中,这里使用div

演示


此外,您可以使用.replaceWith()方法来实现此操作,例如:
$('aside').replaceWith(function () {
    return $('<div/>', {
        html: $(this).html()
    });
});

演示


1
这会因使用.contents时包含的文本节点(空格)而错误地创建多余的div,请参见http://tinker.io/493db/1。 - Nelson
当我在IE8中尝试这个链接时,得到的结果非常不同:http://jsfiddle.net/JpzhL/2/embedded/result/ - Kevin B
我们如何将旧标签的属性应用于新标签?比如说,我有一个 <div class="bullet first" tabindex="0" aria-label="Slide 1" role="button"><span class="visuallyhidden slide-name">Slide 1</span></div> 的HTML标记,我怎样使用 jQuery 将其更改为 <button class="bullet first" tabindex="0" aria-label="Slide 1" role="button"><span class="visuallyhidden slide-name">Slide 1</span></button> - Vikas Khunteta
2
@VikasKhunteta:你可以尝试这个:http://jsfiddle.net/ed6wyed4/ 如果需要进一步帮助,请告诉我。 - palaѕн

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

3

这适用于文档中的每个元素,并且它保留了内容。如果aside元素的内容中有换行符,则使用wraps会导致出现许多div元素。

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


1
这是一种解决方案,可以替换HTML5块标签,保留替换HTML5标签的div元素的样式。仅仅替换标签会使属性丢失。
$('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));
    });

(源标签可能需要更多的工作,它具有“src”和“type”属性)


1
这将完成工作:
 $('aside').replaceWith( "<div>" + $('aside').html() + "</div>" );

同时使用 .html() 方法能够更加灵活地处理内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接