简体   繁体   English

如何使用JavaScript更改HTML标签

[英]How to change a HTML tag using JavaScript

Consider the following code: 考虑以下代码:

var element = document.CreateElement("div");
element.toString(); // [object HTMLDivElement]

var element = document.CreateElement("somerandomtag");
element.toString(); // [object HTMLUnknownElement]

My gut instinct is that once an element has been created, it is essentially "strongly typed" (if such a thing exists in JavaScript), because "div" creates a HTMLDivElement and "somerandomtag" creates a HTMLUnknownElement , thus, the tag cannot be changed, because the created object corresponds directly to that tag. 我的直觉是,一旦创建了元素,它本质上就是“强类型化的”(如果JavaScript中存在这样的东西),因为“ div”创建了HTMLDivElement而“ somerandomtag”创建了HTMLUnknownElement ,因此,标记不能是更改,因为创建的对象直接对应于该标签。

Consider the following code: 考虑以下代码:

var element = document.CreateElement("div");
element.toString(); // [object HTMLDivElement]

element.nodeName = "span"; // Doesn't work.
element.tagName = "span"; // Doesn't work.

So, is it possible to change an element from one type (eg "div") to another type (eg "span") beyond the object's creation? 因此,是否有可能将超出对象创建范围的元素从一种类型(例如“ div”)更改为另一种类型(例如“ span”)?

EDIT: Please note...MUST be done with pure javascript...NO jQuery or other libraries/apis 编辑:请注意...必须使用纯JavaScript完成...没有jQuery或其他库/ API

An element's tagName is readonly (immutable) no matter what the element is. 无论元素是什么,元素的tagName都是只读的(不可变的) You cannot change an element's tag name without some rebuilding of the DOM. 如果不重新构建DOM,就无法更改元素的标签名称。 That is it's not possible to change an existing element, but it's not that difficult to create a new element and append the existing element's children. 那是不可能更改现有元素的,但是创建一个新元素并追加现有元素的子元素并不困难。

var node = document.querySelector('div'),
    newNode = document.createElement('span'),
    parent = node.parentNode,
    children = node.childNodes;

Array.prototype.forEach.call(children, function (elem) {
    newNode.appendChild(elem);
});
parent.replaceChild(newNode, node);

http://jsfiddle.net/ExplosionPIlls/wwhKp/ http://jsfiddle.net/ExplosionPIlls/wwhKp/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM