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?
-
2Are you sure you can't see the search box at the page top right?emerson.marini– emerson.marini2013-07-25 15:30:04 +00:00Commented Jul 25, 2013 at 15:30
-
1developer.mozilla.org/en-US/docs/Web/API/document.createElement && developer.mozilla.org/en-US/docs/Web/API/Node.appendChildIan– Ian2013-07-25 15:30:30 +00:00Commented Jul 25, 2013 at 15:30
Add a comment
|
2 Answers
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:
2 Comments
Mike Phils
var el = document.createElement("elementtype");
Ian
There is no such thing as
prependChild()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
Oriol
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!'));Ian
@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 hereOriol
@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.