jQuery convert DOM element to different type

后端 未结 3 900
自闭症患者
自闭症患者 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:56

    while not a complete solution, the logic would basically be:

    Save your existing element:

    var oldElement = $(your selector here);
    

    create a new element and insert it just before or after your oldElement

    copy the attributes

      oldElement.attr().each(function(){
        copy old
        });
    

    better yet, here is an example of a plug-in that does just what you want:

    http://plugins.jquery.com/project/getAttributes

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-19 03:04

    A more modern (2020+) approach is:

    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
      }

    Compared to @James answer, you don't need to copy the cssText because it's already taken care by the browser. You also don't need the string/number dom properties since those are also properly migrated. It's also best to work on the cloned node only, not both of them (clone and elem)

    0 讨论(0)
提交回复
热议问题