kasperhj
kasperhj

Reputation: 10482

Generating and inserting html with javascript function

I have the following function:

<script>
    function generateHtml(index)
    {
       document.write('Hello ' + index);
    }
</script>

and I have a server side script generating the following html

<div><script>generateHtml(3)</script></div>
<div><script>generateHtml(4)</script></div>

in the hopes that Hello 3 and Hello 4 would be written in the page. However, this does not occur. Instead nothing is displayed. What is wrong with this approach?

Is it better to wrap the <div>'s is a id that can be selected and then change the html instead of writing to the DOM?

Upvotes: 0

Views: 59

Answers (2)

no1spirite
no1spirite

Reputation: 638

For your code to work you must ensure that the html is present on the page after the javascript function

<body>
   <script>
       function generateHtml(index)
       {
           document.write('Hello ' + index);
        }
  </script>

  <div><script>generateHtml(3)</script></div>
  <div><script>generateHtml(4)</script></div>

</body>

To answer your question, using id's to select the DOM elements is certainly a better option.

Maybe a suggestion, use an MVVM framework such as knockout/ember/backbone/angular to do any dynamic DOM manipulation.

Example in knockout here ---> http://jsfiddle.net/x0t8dxzw/

Upvotes: 0

T J
T J

Reputation: 43156

Most probably the <script> containing function generateHtml is added after the other <script>blocks, causing

Uncaught ReferenceError: generateHtml is not defined 

Make sure it's added beforehand so that it works as expected.

Upvotes: 1

Related Questions