16
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?

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Sora
  • 2,465
  • 18
  • 73
  • 146

4 Answers4

18

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.

ruakh
  • 175,680
  • 26
  • 273
  • 307
3

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');
Gabriel Arghire
  • 1,992
  • 1
  • 21
  • 34
1

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.

MarmiK
  • 5,639
  • 6
  • 40
  • 49
  • Are you suggesting (s)he change `style='color:Gray;'` to `style='color:Gray'`? Trust me, that won't make a difference; those notations are 100% equivalent. – ruakh Aug 23 '13 at 06:46
-1

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Imran Khan
  • 129
  • 1
  • 1
  • 8