HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

JavaScript function to change an element tag

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
tagjavascriptfunctionelementchange

Problem

I wrote this JavaScript function to change an element tag name to a div.

function divilize(elem) {
    var elemDiv = document.createElement("div");
    var elemAttrs = elem.attributes;
    for (var attr = 0; attr < elemAttrs.length; attr++)
        elemDiv.setAttribute(elemAttrs[attr].name, elemAttrs[attr].value);
    elemDiv.className += 'divilize-'+elem.tagName.toLowerCase();
    while (elem.firstChild)
        elemDiv.appendChild(elem.firstChild);
    elem.parentNode.replaceChild(elemDiv,elem)
}

divilize(document.getElementById('one'));


Basically, it receives an element, creates a div, copies the attributes, adds in a class with the original tag name for styling purposes (I can make a .divilize-span {display: inline;}), and copies over all of the child elements. I designed with fast reusable code in mind and to avoid losing any event handlers.

Let me know your thoughts...

Solution

You will have a css concatenation issue if the passed element already has a class, for example :



will turn into :



Then on the actual efficiency of the function, I would use standard calls and quicker logic to speed things up :

function divilize(elm) {

   var clone = elm.cloneNode(true);
   var tagName = clone.tagName.toLowerCase(); 

   clone.className += " divilize-"+tagName; 
   elm.outerHTML = clone.outerHTML.replace(tagName, "div");   

}


@ Fiddle

Code Snippets

<div class="test" id="one"></div>
<div class="testdivilize-span" id="one"></div>
function divilize(elm) {

   var clone = elm.cloneNode(true);
   var tagName = clone.tagName.toLowerCase(); 

   clone.className += " divilize-"+tagName; 
   elm.outerHTML = clone.outerHTML.replace(tagName, "div");   

}

Context

StackExchange Code Review Q#158337, answer score: 2

Revisions (0)

No revisions yet.