Created
August 25, 2014 15:27
-
-
Save lsauer/8ec160b96317d86560a7 to your computer and use it in GitHub Desktop.
JavaScript-transformTag: switch/change the HTML DOM tag type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//lsauer.com, 2012; rev. 2014 by lo sauer | |
//description: transformTag fully replaces a node by a different Tag, and re-attaches all children to the newly formed Tag | |
// Any desired EventHandlers must be re-attached manually | |
//@param tagIdOrElem: an HTMLElement Id-Name or an instance of any HTMLElement | |
//[@param tagType]: the HTML Tag Type. Default is 'span' (HTMLSpanElement) | |
function transformTag(tagIdOrElem, tagType){ | |
var elem = (tagIdOrElem instanceof HTMLElement) ? tagIdOrElem : document.getElementById(tagIdOrElem); | |
if(!elem || !(elem instanceof HTMLElement))return; | |
var children = elem.childNodes; | |
var parent = elem.parentNode; | |
var newNode = document.createElement(tagType||"span"); | |
for(var a=0;a<elem.attributes.length;a++){ | |
newNode.setAttribute(elem.attributes[a].nodeName, elem.attributes[a].value); | |
} | |
for(var i= 0,clen=children.length;i<clen;i++){ | |
newNode.appendChild(children[0]); //0...always point to the first non-moved element | |
} | |
newNode.style.cssText = elem.style.cssText; | |
parent.replaceChild(newNode,elem); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Google search page | |
transformTag(document.querySelector('#prm-pt'), 'div') | |
transformTag('most-visited') 'ul') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should also check is the css style empty before copying, otherwise result in a empty 'style' attribute on the new element.
Here is the updated function body: