HTML Tag Swap Demo

In reponse to a posting on the Webmaster Talk Forum requesting information about how to convert one tag into another using javascript, I created this little demo. Since a tag can not actually be transformed (as far as I know) the next best thing is to create a new tag, give it all of the previous tag's child elements and swap the two the two tags.

google

Source:

  1. <script type="text/javascript">
  2. /* <![CDATA[ */
  3.  
  4. function transformTag(tagId){
  5.   var elem = document.getElementById(tagId);
  6.   var children = elem.childNodes;
  7.   var parent = elem.parentNode;
  8.   var newNode = document.createElement("span");
  9.   for(var i=0;i<children.length;i++){
  10.     newNode.appendChild(children[i]);
  11.   }
  12.   parent.replaceChild(newNode,elem);
  13. }
  14.  
  15. /* ]]> */
  16. </script>
  17.  
  18. </head>
  19.  
  20. <body>
  21. <h1>Demo tag swap</h1>
  22. <a id="googLink" href="http://google.com">google</a>
  23. <hr />
  24.  
  25. <formaction="#">
  26. <input type="button" onclick="transformTag('googLink');" value="transform" />
  27. </form>

Code Explained

In line 12, the variable elem is assigned to the node to be replaced. Next, (line 13) we get the array of child nodes, and a reference to the parent node(line 14). On line 15, the new element is created. The child nodes are then moved to the new node (lines 16-18) using a loop. Finally, the node is swaped with the new one (line 19).

The HTML for the demonstration just 'converts' an anchor tag into span tag (as suggested in the posting). Note the anchor tag on line 19 with an id of googLink and the function call on the button (line 33) that passes the anchor tag's id to the swap function.

Questions, comments, insults? Post a reply to the original posting or send an email to feedback@willcode4beer.com.



Sponsors:

About willCode4Beer