如何在jquery中用另一个标签替换HTML标签?
我有一个我正在研究的网站,它使用’旁边’标签,即使使用HTML5 Shiv,无论我尝试什么,我都无法读取IE8。 所以,我想知道,你如何用jQuery替换其他标签的现有标签?
例如,如果我想改变
至
怎么做?
试试这个:
$('aside').contents().unwrap().wrap('');
- 首先获取
aside
的内容。 - 现在
unwrap
内容。 - 现在简单地
wrap
内容wrap
在一个新标签内,这里是一个div
。
DEMO
此外,您可以使用.replaceWith()
方法执行此操作,如:
$('aside').replaceWith(function () { return $('', { html: $(this).html() }); });
DEMO
$('aside').replaceWith('');
这适用于文档中的每个元素,并保留内容。 如果在aside
元素的内容中有换行符,则使用换行会导致出现许多div
元素。
$('aside').each(function() { $(this).replaceWith("
"+$(this).html()+"
") });
这将完成工作:
$('aside').replaceWith( "" + $('aside').html() + "" );
使用.html()也可以提供更加动态的方法。
这是一个替换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($('').html(html).attr(attrs)); });
(可能需要对源标记进行更多的工作,源标记具有“src”和“type”属性)