jQuery convert DOM element to different type

后端 未结 3 901
自闭症患者
自闭症患者 2020-12-19 02:43

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 attribut

3条回答
  •  攒了一身酷
    2020-12-19 02:58

    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;
    }
    

    E.g.

    makeNewElementFromElement('a', someDivElement); // Create anchor from div
    

提交回复
热议问题