Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'String contains an invalid character' when using document.createElement()

Tags:

javascript

var NewRow = document.createElement("<tr><td align='left' valign='top'  width='9%;'  ><img width='32px' height='32px' src='images/" + ProfilePic + "'  /></td><td align='left' valign='Top' ><span class='MsgSpan'>" + Msg + "</span></td><td align='right' align='left' valign='top' style='color:Gray;' >" + Date + "</td></tr>");

I am getting an error:

InvalidCharacterError: String contains an invalid character

How can I fix this?

like image 501
Sora Avatar asked Aug 23 '13 06:08

Sora


3 Answers

In my case I had an extra space when adding a css class to a div.

I had this

menuLinksDiv.classList.remove('show-element ');

Removed the space after show-element string and no error

menuLinksDiv.classList.remove('show-element');
like image 185
Justice Bringer Avatar answered Nov 15 '22 15:11

Justice Bringer


The string you pass to document.createElement is the type of the element, e.g. tr.

If you really want to assemble your HTML as a big string, I suppose you could write:

var newRow = document.createElement('tr');
newRow.innerHTML = "<td align='left' valign='top'  width='9%;'  ><img width='32px' height='32px' src='images/" + ProfilePic + "'  /></td><td align='left' valign='Top' ><span class='MsgSpan'>" + Msg + "</span></td><td align='right' align='left' valign='top' style='color:Gray;' >" + Date + "</td>";

but it's probably cleaner/faster/safer to use DOM manipulation for the whole thing.

like image 39
ruakh Avatar answered Nov 15 '22 14:11

ruakh


I have one similar answer below: Here, I have defined the elements in HTML and not created them separately, so that it will be easy to change and debug.

var ProfilePic = "abl.jpg";
var Msg="Hi";
var Date = "June 10, 2010";
function doit() {
   var NewRow ="<tr><td align='left' valign='top'  width='9px'  ><img width='32px' height='32px' src='images/" + ProfilePic + "'  /></td><td align='left' valign='Top' ><span class='MsgSpan'>" + Msg + "</span></td><td align='right' align='left' valign='top' style='color:Gray;' >" + Date + "</td></tr>";
   var element = document.getElementById("tbl_body");
   element.innerHTML +=NewRow;
}

The problem with the previous code was createElement where you have to create row, then td then text and then append.

like image 1
MarmiK Avatar answered Nov 15 '22 14:11

MarmiK