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?
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?
Share Improve this question edited Jan 10, 2018 at 15:51 mikemaccana 123k110 gold badges427 silver badges531 bronze badges asked Aug 23, 2013 at 6:38 SoraSora 2,55119 gold badges77 silver badges150 bronze badges4 Answers
Reset to default 20The 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.
Check extra space after class name
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');
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.
Check this out:
Creating a new DOM element from an HTML string using built-in DOM methods or Prototype
You can not pass HTML string to createElement method, instead use innerHTML property as shown in the above link.