Charles Fecht
Charles Fecht

Reputation: 47

Insert html into web page using javascript's .innerHTML

I am making a template for a web site, and decided to try to use an external JS file to insert html into the top of the page for navigation (instead of having to copy and paste it every time)

I am trying to use (as the title states) The .innerHTML tag to do this so I can edit the code in whole.

Here it is:

JavaScript

document.getElementById("insert").innerHTML += '<script         language="javascript"> 
function toggle() {
var ele = document.getElementById("toggleText");
var text = document.getElementById("displayText");
if(ele.style.display == "inline") {
        ele.style.display = "none";
    text.innerHTML = '<img src="http://www.psdgraphics.com/file/down-    arrow-icon.jpg" height="25" width="25">';
}
else {
    ele.style.display = "inline";
    text.innerHTML = '<img src="http://www.psdgraphics.com/file/up-arrow-icon.jpg" height="25" width="25">';
}
} 
</script>
<body>

 <a id="displayText" href="javascript:toggle();"><img     src="http://www.psdgraphics.com/file/down-arrow-icon.jpg" height="25" width="25"></a><span style="text-size: 30px;">Logo</span>

<div id="toggleText" class="navbar" style="display: none">
<div style="background-color: #8CBADB; text-align:center; height:25px; width:250px; border: .5px solid black;">
<a href="#">Home</a>
<a href="#">About</a></div>
</div>
<br>
Content';


HTML

 <!DOCTYPE html>
 <html>
 <head>
  <meta charset="utf-8">
  <title></title>
   </head>
  <div id="insert"></div>
</body>
</html>



I have double checked that I escaped the quotes, I ran it through JSLint, and checked for possible syntax errors. I have so far come up with nothing.

What am I going wrong?

Upvotes: 0

Views: 1835

Answers (2)

Tushar
Tushar

Reputation: 26

I see two problems in your code:

  1. You need to assign only in line no 1, remove the concatenation sign +

    document.getElementById("insert").innerHTML +=

  2. At line no 7 and 11 avoid using single single quote, instead that use double quotes, It's making the wrong syntax, because it will make end of the expression here.

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85633

You need to assign but not to concatenate.

document.getElementById("insert").innerHTML += 
// Remove + from here----------------------^^

Upvotes: 1

Related Questions