You have two options here.
The DOM way
This is the way that you are searching for with createElement
. It is the best way in a sense, because it allows you to interact with the DOM as it already exists. You don't however need createElement
: you should really use createTextNode
, which does what it says on the tin:
function myFunction() {
var name = prompt("Enter some text:"),
node = document.createTextNode(name);
document.getElementById('latest').appendChild(node);
}
(This results in adding the text to the end of the element: it does not remove the content that is already there.)
The realistic way
While using the DOM functions is all well and good, it is not really idiomatic Javascript. In reality, innerHTML
is the property you should probably be using. Browsers are really good at parsing HTML (it's what they're built for, after all!) so this will almost certainly be quicker than the DOM method.
function myFunction() {
var name = prompt("Enter some text:");
document.getElementById('latest').innerHTML = name; // to overwrite the existing contents
document.getElementById('latest').innerHTML += name; // to add to the existing contents
}
There are other ways, such as using createDocumentFragment
, but this second method is almost certainly the way for you to go.