如何使用 JavaScript 更改 HTML 标记

2022-01-18 00:00:00 tags javascript html

考虑以下代码:

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

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

我的直觉是,一旦创建了一个元素,它本质上就是强类型"(如果 JavaScript 中存在这样的东西),因为div"创建了一个 HTMLDivElement 和somerandomtag"创建一个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.

考虑以下代码:

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

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

那么,除了对象的创建之外,是否可以将元素从一种类型(例如div")更改为另一种类型(例如span")?

So, is it possible to change an element from one type (e.g. "div") to another type (e.g. "span") beyond the object's creation?

请注意...必须使用纯 javascript...NO jQuery 或其他库/apis

Please note...MUST be done with pure javascript...NO jQuery or other libraries/apis

推荐答案

一个元素的 tagName 是只读的(不可变的) 无论元素是什么.如果不对 DOM 进行一些重建,就无法更改元素的标签名称.也就是说,无法更改现有元素,但创建新元素并附加现有元素的子元素并不难.

An element's tagName is readonly (immutable) no matter what the element is. You cannot change an element's tag name without some rebuilding of the 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/

相关文章