我正在开发一个网站,其中使用了“aside”标签,但无论我尝试什么方法,包括使用HTML5 Shiv,都无法让IE8识别它们。因此,我想知道,如何使用jQuery将现有的标签替换为其他标签?
例如,如果我想要更改:
<aside>
<h3></h3>
</aside>
to
<div>
<h3></h3>
</div>
那应该怎么做呢?
试试这个:
$('aside').contents().unwrap().wrap('<div/>');
aside
的内容。unwrap
操作。div
。.replaceWith()
方法来实现此操作,例如:$('aside').replaceWith(function () {
return $('<div/>', {
html: $(this).html()
});
});
.contents
时包含的文本节点(空格)而错误地创建多余的div
,请参见http://tinker.io/493db/1。 - Nelson<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$('aside').replaceWith('<div><h3></h3></div>');
这适用于文档中的每个元素,并且它保留了内容。如果aside
元素的内容中有换行符,则使用wraps
会导致出现许多div
元素。
$('aside').each(function() {
$(this).replaceWith("<div>"+$(this).html()+"</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”属性)
$('aside').replaceWith( "<div>" + $('aside').html() + "</div>" );
同时使用 .html() 方法能够更加灵活地处理内容。
document.createElement('aside')
应该可以让您在 IE8 中使用 aside 标签。您正在使用 html5 doctype,对吗? - Kevin B<aside>foo</aside>
变成了<aside/>foo</aside/>
,因此替换可能会更加困难一些。 - Kevin B