0

Is it possible to generate html from JavaScript? For example, I have this:

    <script type="text/javascript">
    for (i=0; i<=length; i++)
      {
        //I want to display a <p> tag containing the value of i
      }  
    </script>

So the generated html should look something like this if length = 5:

    <p>0</p>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
    <p>5</p>

Is it possible to do this?

0

7 Answers 7

5

Very possible. You would insert the elements into the DOM:

var NewP;
var Text;

for(var i = 0; i < 5; i++)
{
    NewP = document.createElement("p"); // Create a p element
    Text = document.createTextNode(i + ""); // Create text to go inside with string value of i
    NewP.appendChild(Text); // Add text to p element
    document.body.appendChild(NewP); // Append newly-created p element to body element in DOM tree
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I needed! Thanks!!! I'll accept the answer when it allows me to do so.
If I wanted to create a link instead, how would I add that?
1
<SCRIPT LANGUAGE="JavaScript">
<!--
greeting = "<H1>Hi Web surfers!</H1>"
welcome = "<P>Welcome to <CITE>stackoverflow.com</CITE>.</P>"
// -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
document.write(greeting)
document.write(welcome)
// -->
</SCRIPT>

Comments

1

Sure. Your code would look like this:

<script type="text/javascript">
var total = 5;
for (i=0; i <= total; i++)
  {
    document.write('<p>' + i + '</p>');
  }  
</script>

Comments

0

Yes. It's possible. For example:

<script type="text/javascript">
  var html = "";
  for (i=0; i<=6; i++) {
      html += "<p>" + i + "</p>";
  } 
  document.write(html);
</script>

Comments

0

You can put document.write('<p>' + i + '</p>'); in your loop

Comments

0

Yes, it is possible:

http://www.java2s.com/Code/JavaScript/HTML/GeneratingHTMLOntheFly.htm

but there are some nice plugins that facilitate the process better, specially if you intend to do more of this:

http://api.jquery.com/category/plugins/templates/

http://akdubya.github.com/dustjs/

Comments

-2

You can make a <div id="div"></div>in your html and simply in the function:

$("#div").html('<p>'+i+'</p>');

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.