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.

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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>

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.