jQuery将DOM元素转换为不同类型

问题描述:

我需要将DOM元素转换成不同的类型(如HTML标签名称 a p 在这种情况下),但仍保留所有原始元素属性。在这种情况下,它们是否适用于新的类型无关紧要。

I need to convert a DOM element to a different type (as in HTML tag name, a to p in this case), but still retain all the original elements attributes. Whether they are valid for the new type or not doesn't matter in this case.

有关如何执行此操作的任何建议?

Any suggestions on how to do this?

我已经看过只是创建一个新的元素并复制属性,但这并不是没有它自己的并发症。在Firefox中, DOMElement.attributes 只能包含具有值的属性,但在IE中报告该元素的所有可能属性。 属性属性本身是只读的,所以没有办法复制。

I've looked at just creating a new element and copying the attributes across, but this isn't without it's own complications. In Firefox, DOMElement.attributes helpfully only includes attributes with a value, but in IE it reports all possible attributes for that element. The attributes property itself is read-only, so no way to copy that.

Sans-jQuery解决方案:

Sans-jQuery solution:

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