1

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?

3

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.