Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to include HTML code in JavaScript?

I have a basic question, can I include HTML code in JS? (with document.write)

This is my HTML code:

<li><a href="#" class="menulink">text</a></li>
<li><a href="#" class="menulink">text</a></li>
<li>
  <a href="#" class="menulink">text</a>
  <ul>
    <li>
      <a href="#" class="sub">text</a>
      <ul>
        <li class="topline"><a href="#">text</a></li>
        <li><a href="#">text</a></li>
        <li><a href="#">text</a></li>
        <li><a href="#">text</a></li>
        <li><a href="#">text</a></li>
        <li><a href="#">text</a></li>
        <li><a href="#">text</a></li>
      </ul>
    </li>
    <li>
      <a href="#" class="sub">text</a>
      <ul>
        <li class="topline"><a href="#">text</a></li>
        <li><a href="#">text</a></li>
      </ul>
    </li>

    <li>
      <a href="#" class="sub">text</a>
    </li>
    <li>
      <a href="#" class="sub">text</a>
    </li>
  </ul>
</li>

<li>
  <a href="#" class="menulink">text</a>
</li>
<li><a href="#" class="menulink">text</a></li>

And I want to include it in this JS code:

window.onload = function () {
  document.getElementById("menu").innerHTML="";
}

Connect it by this code:

<p id="dropdown_menu"></p>

How can I do it?

The full code is here http://jsfiddle.net/tsnave/eSgWj/4/ thanks..

like image 926
Nave Tseva Avatar asked Aug 31 '12 13:08

Nave Tseva


1 Answers

A different way of doing it is to put the HTML inside a script tag:

<script type="text/template" id="myHtml">
    <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>
</script>

Then you can get it into Javascript using

var myHtml = document.getElementById('myHtml').innerHTML;

or using one of several libraries which help you with this. Code inside a script tag with type="text/template" will not be interpreted or shown by the browser. The advantage of this approach over putting it straight into a string in Javascript is that it allows you to keep treating it as normal HTML in your editor, and it keeps the Javascript clean. See also this post by John Resig.

like image 173
Supr Avatar answered Sep 21 '22 13:09

Supr