Tuesday, July 21, 2015

Uncaught InvalidCharacterError: Failed to execute 'createElement' on 'Document': The tag name provided ('') is not a valid name.(anonymous function) @ (index):62

Getting following error while calling an old javascript method which dynamically creates a column in a table.

Uncaught InvalidCharacterError: Failed to execute 'createElement' on 'Document': The tag name provided ('<TD class="column" style="white-space:nowrap; text-align:right;">') is not a valid name.(anonymous function) @ (index):62

I reproduced the same on jsfiddle with following code (http://jsfiddle.net/sanjayingole/068ut9tp/1/)

<div id="employeeDiv" class="tableDiv empDiv">
    <table id="employeeTable">    
    </table>
</div>

<!-- Javascript to dynamically create TD tag-->
<script>
var newTable=document.getElementById("employeeTable");

newtablebody = document.createElement("TBODY");
newRow   = document.createElement("TR");

//The Javascript tries to create the TD element with some html code. 
//Which is causing this error.
newCell = document.createElement("<TD class=\"column\" style=\"white-space:nowrap; text-align:right;\">");


textNode = document.createTextNode(displayname);
newCell.appendChild(textNode);
newRow.appendChild(newCell);

</script>

Solution:

Initially I suspected the double quotes was causing the problem and changed it to single quotes instead, but that dint solve the problem either.
Following worked fine :
Instead of creating elements like :

              document.createElement("<TD class=\"column\" style=\"white-space:nowrap; text-align:right;\">");

use following :

newCell = document.createElement("TD");   
newCell.setAttribute("style", "white-space:nowrap; text-align:right;");

Following example shows the fix :
http://jsfiddle.net/sanjayingole/068ut9tp/3/


Personally Jquery would be a lot convenient to implement dynamic components. For example datatables are very easy to implement and rendering part is taken care of by jquery.

No comments:

Post a Comment