Junaid S.
Junaid S.

Reputation: 2652

Make Html page using javascript dynamically

I go through following links

How can I make JavaScript make (produce) new page?

Create and append dynamically

I want to add html elements dynamically with JavaScript inside a div but I donot want to follow 2nd link because my javascript code will become very big and complex. Is there a way so that I can add html elements using one line of code as done in 1st link.

I donot want to use JQuery.

Upvotes: 1

Views: 2046

Answers (3)

Akshay Khale
Akshay Khale

Reputation: 8371

Here is simplest option you can have

   <script>
    var htmlcontent = "<h1>Header</h1><p>This is some dynamically loaded content assigned using javascript</p>"
    document.getElementById("content").innerHTML = htmlcontent;
   </script>

Upvotes: 0

Himesh Aadeshara
Himesh Aadeshara

Reputation: 2131

here what i want to say you can use like this

var element = document.getElementsByTagName("body"); // Pick your element here as per need.

var attach_elem = "<div><p> hi creatig the p tag </p> <span>  hi creatig the span tag </span><div></div></div>"; //prepare element which you want to be in your html page.

element.write(attach_elem); // just pass the variable (want to attach in html).


//Or you can use the below code.

element.innerHTML = attach_elem; // pass variable as innerhtml to the selected element.

Upvotes: 0

Nitsew
Nitsew

Reputation: 3662

First I am going to start by saying, Use jQuery. If you use jQuery you literally only need to do this:

$("#target").append("<p>New Paragraph</p>");

If you insist on using vanilla JavaScript, you will have to do like the second example you posted does it:

var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

Upvotes: 2

Related Questions