0

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?

2
  • Why are you using this approach? you can generate htmls directly by server side scripts Commented Aug 31, 2014 at 8:17
  • True. The reason is that this only represent the persisted state. In my application there are two states (free and occupied), and there will be some ajax to change between the states. By having this done by javascript, I hope to avoid duplicating the html for the two states. Commented Aug 31, 2014 at 8:23

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the fiddle. It turned out that I had a "text/javascript" in my code (which I omitted for the demonstration) that appeared to cause the problem.,
0

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/

1 Comment

I will go for the selector solution instead I think. Thanks.

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.