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

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 get an error message:

 InvalidCharacterError: String contains an invalid character 

How can i fix this?

+6
source share
3 answers

The string passed in document.createElement is the type of the element, for example. tr .

If you really want to assemble your HTML as a large 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 perhaps cleaner / faster / safer to use DOM manipulation for everything.

+10
source

A recent answer will be fine. I have one similar answer. I defined the elements so that they were easy to 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; } 

it works like a charm for me .. the problem with the previous code was createElement .. but it will work yet you need to create a line, then td, then text and add them ...

I hope this is done.

0
source

Check this:

Create a new DOM element from an HTML string using inline methods or a DOM prototype

You cannot pass an HTML string for the createElement method, use the innerHTML property instead, as shown in the link above.

0
source

Source: https://habr.com/ru/post/952336/


All Articles