1

Perhaps there's a better way to word my question by saying "Dynamically create DOM elements via Javascript", but I decided to write the simple title in case the latter was wrong. Anyway, is there a way I can "spawn" HTML elements via Javascript? For example, I can click a button on my site, and a paragraph will appear?

2

2 Answers 2

5

You can use createElement() like this:

var el = docment.createElement("elementtype");

This will create any element, if you replace elementtype with the type of element ("div", "p", etc.)

After that, you can use the native .appendChild() or .insertBefore() methods on whichever element you want to attach this new created element onto.

var attachTo = document.getElementById('appendToMe');
attachTo.appendChild(el);

And it'll be on the page after the last element inside of that element.

References:

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

2 Comments

var el = document.createElement("elementtype");
There is no such thing as prependChild()
1
var element = document.createElement('p');
element.innerHTML = "Hey, this is a new paragraph!";
parentElement.appendChild(element);

For more information, refer to document.createElement and Node.appendChild

3 Comments

Just a note: innerHTML is widely supported, but it isn't a w3c standard yet because it's part of HTML5 DOM, a Working Draft (however, it's a whatwg Living Standard). With current w3c standards, it should be element.appendChild(document.createTextNode('Hey, this is a new paragraph!'));
@Oriol That's one of the most trivial things I've ever heard. innerHTML is so widely supported that standards shouldn't even be a factor for something like this. I agree that document.createTextNode should be used for something like this example, and in most scenarios (although you could easily use textContent/innerText), but citing W3C isn't really applicable here
@Ian I just thought that if asker didn't know how to create an element, he wouldn't know that innerHTML isn't standard yet. And I think that, even if it's widely supported, everybody who use non-standard things should be aware of it.

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.