HTML and CSS Reference
In-Depth Information
be able to use it again later, you can simply hide it by using the appropriate CSS rather than
remove it. Here's an example:
var element = document.getElementById("innerDiv");
alert(element.innerHTML);
document.removeChild(element);
var afterRemove = document.getElementById("innerDiv");
alert(afterRemove);
The first
alert
properly shows the
innerHTML
property of the
innerDiv
, but the code never
reaches the second alert. Instead, the
getElementById
method throws an error because the
element
id
specified no longer exists in the document.
Be aware of various methods when it comes to adding elements to and removing them
from the DOM.
The first method to look at is
document.createElement
. You use this method of the
document
object to create a new HTML element. The method receives a single parameter—
the element name of the element you want to create. The following code creates a new
<article>
element to use in your page:
var element = document.createElement("article");
element.innerText = "My new <article> element";
This new
<article>
element isn't visible to anyone at this point; it merely exists in the DOM
for use within your page. Because you don't have much need to create elements but then not
use them, next look at the methods available to get your new
<article>
element into your
page. The first of these methods is
appendChild
. You use this method to add a new HTML
element to the collection of child elements belonging to the calling container. The node is
added to the end of the list of children the parent node already contains. The
appendChild
method exists on the document object as well as on other HTML container elements. It returns
a reference to the newly added node. This example appends a new
<article>
element to the
outerDiv
:
var outerDiv = document.getElementById("outerDiv");
var element = document.createElement("article");
element.innerText = "My new <article> element";
outerDiv.appendChild(element);
Like most of the other methods explained in this section, the
appendChild
method returns
a reference to the new element appended to the child elements. This is a good way to ensure
that you always have a reference to an element for future use, especially when deleting ele-
ments. It also enables you to simplify or restructure the code. The following code achieves the
same result:
var element = document.getElementById("outerDiv").appendChild(document.
createElement("article"));
element.innerText = "My new <article> element";
Search WWH ::
Custom Search