Shyamal Parikh
Shyamal Parikh

Reputation: 3068

Inserting HTML text in js code

How do I import a html file in to javascript code?

Currently I have to do something like:

document.getElementById("menu").innerHTML = '<li class="topline"><a href="#">some text</a></li>  
                <li><a href="#">some text </a></li>  
                <li><a href="#">some text</a></li>  
                <li><a href="#">some text</a></li>  
                <li><a href="#"some text</a></li>  
                <li><a href="#">some text</a></li>  
                <li><a href="#">some text</a></li>';

How do I separate the js code and html code in to separate files. Later load the html code into javascript easily?

Upvotes: 1

Views: 87

Answers (2)

Naren Murali
Naren Murali

Reputation: 56182

You can do this. Taken from the below reference link.

You need to put the ul and li tags inside a file called import.htm, also it needs to be in the same place as the current file.

var ajax = new XMLHttpRequest();
ajax.open("GET", "import.htm", false);
ajax.send();
document.getElementById("menu").innerHTML += ajax.responseText;

Reference:

  1. JavaScript import HTML

Upvotes: 1

Mr. Pyramid
Mr. Pyramid

Reputation: 3935

Just like this

$("#menu").load('menu.html #menulist');

then in HTML file do this

<ul id ="menulist">
<li class="topline"><a href="#">some text</a></li>  
<li><a href="#">some text </a></li>  
<li><a href="#">some text</a></li>  
<li><a href="#">some text</a></li>  
<li><a href="#"some text</a></li>  
<li><a href="#">some text</a></li>  
<li><a href="#">some text</a></li>
</ul>

For better reference

Click Here

Upvotes: 0

Related Questions