jQuery convert DOM element to different type

后端 未结 3 904
自闭症患者
自闭症患者 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 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)

提交回复
热议问题