javascript 动态更改 HTML 元素类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8721471/
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
Dynamically change a HTML elements type
提问by sazr
I am wondering if its possible to change a HTML elements data type with javascript?
我想知道是否可以使用 javascript 更改 HTML 元素数据类型?
For example change an img to a div? The reason I am doing this & not destroying the img & creating a div is because the element contains A LOT of inline styling so I would need to copy all the inline style from the img to the div. PS: this website is only for iPad, so cross-browser compatibility is not an issue.
例如将 img 更改为 div?我这样做的原因 & 不破坏 img & 创建一个 div 是因为该元素包含很多内联样式,所以我需要将所有内联样式从 img 复制到 div。PS:本网站仅适用于iPad,因此跨浏览器兼容性不是问题。
var div = img.cloneNode(true);
div.type = "div";
So it would be easier to clone the node/element using img.cloneNode(true), then must change the type to a div. I hope this is possible?
因此使用 img.cloneNode(true) 克隆节点/元素会更容易,然后必须将类型更改为 div。我希望这是可能的吗?
If not maybe there is a easy way to copy one elements style to another elements? Maybe...
如果不是,也许有一种简单的方法可以将一个元素样式复制到另一个元素?或许...
// img is an img HTML element
var div = document.createElement("div");
div.style = img.style;
document.body.removeChild(img); // does that destroy div.style aswell?
采纳答案by ron tornambe
You cannot change the type of an element. Yes, the div's style will be overwritten unless you concatenate div.style+=img.style. In this case like img style attributes override the div's.
您不能更改元素的类型。是的,除非您连接 div.style+=img.style,否则 div 的样式将被覆盖。在这种情况下,像 img 样式属性会覆盖 div。
回答by SpoonNZ
I'd try the second manner - I'd think it shouldwork, and it should be super quick to try it out - probably quicker than asking on here was!
我会尝试第二种方式 - 我认为它应该有效,而且尝试起来应该非常快 - 可能比在这里提问要快!
Edit: I can confirm it does NOT work (at least, not in Opera). JSFiddle at http://jsfiddle.net/T7r5c/
编辑:我可以确认它不起作用(至少在 Opera 中不起作用)。JSFiddle 在http://jsfiddle.net/T7r5c/