我需要将DOM元素转换为其他类型(如HTML标记名称,在这种情况下为a
至p
),但仍保留所有原始元素属性。在这种情况下,它们对于新类型是否有效都无关紧要。
关于此操作的任何建议?
我看过只是创建一个新元素并复制属性,但这并不是没有它自己的复杂性。在Firefox中,DOMElement.attributes
仅有助于包含带有值的属性,但在IE中,它将报告该元素的所有可能的属性。 attributes
属性本身是只读的,因此无法复制它。
Sans-jQuery解决方案:
function makeNewElementFromElement( tag, elem ) {
var newElem = document.createElement(tag),
i, prop,
attr = elem.attributes,
attrLen = attr.length;
// Copy children
elem = elem.cloneNode(true);
while (elem.firstChild) {
newElem.appendChild(elem.firstChild);
}
// Copy DOM properties
for (i in elem) {
try {
prop = elem[i];
if (prop && i !== 'outerHTML' && (typeof prop === 'string' || typeof prop === 'number')) {
newElem[i] = elem[i];
}
} catch(e) { /* some props throw getter errors */ }
}
// Copy attributes
for (i = 0; i < attrLen; i++) {
newElem.setAttribute(attr[i].nodeName, attr[i].nodeValue);
}
// Copy inline CSS
newElem.style.cssText = elem.style.cssText;
return newElem;
}
例如
makeNewElementFromElement('a', someDivElement); // Create anchor from div
虽然不是完整的解决方案,但逻辑基本上是:
保存您现有的元素:
var oldElement = $(your selector here);
创建一个新元素并将其插入到oldElement之前或之后
复制属性
oldElement.attr().each(function(){
copy old
});
更好的是,这是一个可以满足您需要的插件的示例:
[更现代(2020+)的方法是:
function changeTag (element, tag) {
// prepare the elements
const newElem = document.createElement(tag)
const clone = element.cloneNode(true)
// move the children from the clone to the new element
while (clone.firstChild) {
newElem.appendChild(clone.firstChild)
}
// copy the attributes
for (const attr of clone.attributes) {
newElem.setAttribute(attr.name, attr.value)
}
return newElem
}
与@James答案相比,您不需要复制cssText
,因为浏览器已经处理过了。您也不需要字符串/数字dom属性,因为这些属性也已正确迁移。最好只在克隆的节点上工作,而不要同时在两个节点(克隆和elem)上工作]