jQuery 你如何用jquery中的另一个标签替换一个HTML标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16285791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you replace an HTML tag with another tag in jquery?
提问by Paul L
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?
我有一个我正在处理的网站,它使用“aside”标签,无论我尝试什么,即使使用 HTML5 Shiv,我也无法让 IE8 阅读。所以,我想知道,您将如何使用 jQuery 将现有标签替换为其他标签?
For example, if I wanted to change
例如,如果我想改变
<aside>
<h3></h3>
</aside>
to
到
<div>
<h3></h3>
</div>
How would that be done?
那怎么办?
回答by pala?н
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 adiv
.
- 先获取内容
aside
。 - 现在
unwrap
的内容。 - 现在简单地说,
wrap
新标签内的内容,这里是一个div
.
Also, you can do this using .replaceWith()
method like:
此外,您可以使用以下.replaceWith()
方法执行此操作:
$('aside').replaceWith(function () {
return $('<div/>', {
html: $(this).html()
});
});
回答by Memolition
$('aside').replaceWith('<div><h3></h3></div>');
回答by Gautam Singh
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.
这适用于文档中的每个元素,并保留内容。div
如果元素的内容中有换行符,则使用换行会导致出现许多元素aside
。
$('aside').each(function() {
$(this).replaceWith("<div>"+$(this).html()+"</div>")
});
$('aside').each(function() {
$(this).replaceWith("<div>"+$(this).html()+"</div>")
});
回答by zaphodb
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.
这是替换 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));
});
(may need a little more work on the source tag, which has "src" and "type" attributes)
(可能需要对具有“src”和“type”属性的源标签做更多的工作)
回答by alokrajiv
This will do the job:
这将完成这项工作:
$('aside').replaceWith( "<div>" + $('aside').html() + "</div>" );
Also using the .html() gives a more dynamic approach.
还使用 .html() 提供了一种更动态的方法。