1

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.

Community
  • 1
  • 1
Junaid
  • 2,572
  • 6
  • 41
  • 77

3 Answers3

2

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);
Nitsew
  • 3,612
  • 1
  • 15
  • 20
0

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.
Himesh Aadeshara
  • 2,114
  • 16
  • 26
0

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>
Akshay Khale
  • 8,151
  • 8
  • 50
  • 58