Javascript Output HTML

htmljavascript

I was wondering if someone could help me with this simple code I am trying to make a banner appear at the top of a webpage for cookies policy (click to agree etc) I have coded the PHP part fine and it makes and detects if cookie policy is agreed however I am having problems using a JS snippet to load the banner to the top of my page.

This is what I am using to display the box and for the example about the code works fine displaying a hyperlink or text (as below) but if I try and add any other type of HTML for example a simple table like this it wont work.

<table>
  <tr>
    <td>Test</td>
    <td>Table </td>
  </tr>
</table>

Sorry updated works with hyperlink

<script type="text/javascript">
function changeText()
{
     document.getElementById("new_coder").innerHTML = '<a href="#">sdsd</a>';
}
</script>
<b id='new_coder'>Good Bye World</b>
<input type='button'  value='Change Text'/>

This is what I am trying to do

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function changeText()
{
     document.getElementById("new_coder").innerHTML = '<table>
  <tr>
    <td>Test</td>
    <td>Table </td>
  </tr>
</table>';
}
</script>
<b id='new_coder'>Good Bye World</b>
<input type='button' onclick='changeText()' value='Change Text'/>
<body>
</body>
</html>

Is there a better function for loading HTML snippets into a page via JavaScript. Sorry I am little sketchy on this area.

Thanks Debs

Best Solution

You have actually encountered a javaScript quirk.

JS has automatic semicolon insertion and what it does is insert on line feed.

if you write your function like this:

JSfiddle

function changeText()
{
     document.getElementById("new_coder").innerHTML = "<table><tr><td>Test</td><td>Table </td></tr></table>";
}

It will work.

notice no line break in code

You can get a clue by pressing F12 and looking at your console.

Uncaught SyntaxError: Unexpected token < 

Just around where you had your line break.