Skip to content

Instantly share code, notes, and snippets.

@lsauer
Created August 25, 2014 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsauer/8ec160b96317d86560a7 to your computer and use it in GitHub Desktop.
Save lsauer/8ec160b96317d86560a7 to your computer and use it in GitHub Desktop.
JavaScript-transformTag: switch/change the HTML DOM tag type
//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);
}
//Google search page
transformTag(document.querySelector('#prm-pt'), 'div')
transformTag('most-visited') 'ul')
@hamxiaoz
Copy link

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:

// Rename a tag (change tag type). Ex, <div> -> <a>
function renameTag(target, newNode) {
  // copy attributes
  for (var i = 0; i < target.attributes.length; i++) {
    newNode.setAttribute(
      target.attributes[i].nodeName,
      target.attributes[i].nodeValue
    );
  }

  // move children. firstChild is a live API so we can 'while' on that
  while (target.firstChild) {
    newNode.appendChild(target.firstChild);
  }

  // copy in-line styles
  if (target.style.length > 0) {
    newNode.style.cssText = target.style.cssText;
  }

  return target.parentNode.replaceChild(newNode, target);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment