Changing Page Elements with the DOM

Learn how to use the JavaScript DOM to alter the content of your Web pages. This article shows you how to change element content, how to add and remove elements in the page, how to move elements around, and how to work with element attributes.

So far, you've looked at how to get hold of page elements using JavaScript and the DOM, and how to look inside those elements to retrieve their contents.

In this tutorial, you'll take your skills a step further, and learn how to change elements. You'll see how to:

  • Change the content inside an element
  • Add and remove elements in the page
  • Move an element to a different position in the page, and
  • Manipulate element attributes.

Once you know how to manipulate DOM elements you can start creating flexible, JavaScript-generated Web content.

Changing the contents of an element

In the last tutorial you learned how to read the contents of an element using properties such as childNodes, firstChild, and nodeValue. As well as reading the value of a node with the nodeValue property, you can also change its value simply by assigning a new value to nodeValue.

For example, say your page contains a paragraph element inside a div element:


<div id="welcome"><p>Welcome to the Widget Company!</p></div>

You already know that you can read the text inside the paragraph using:


var welcome = document.getElementById( "welcome" );
alert( welcome.firstChild.firstChild.nodeValue );

Changing the paragraph's text is as simple as assigning a new value to the child text node's nodeValue property:


var welcome = document.getElementById( "welcome" );
welcome.firstChild.firstChild.nodeValue = "Welcome to Widgets R Us!";

What if you want to make more radical changes to your page? Let's say you want to add a horizontal rule (hr) element after the paragraph. To do this, you can't just change a node's nodeValue. Instead, you need to add a new child element to the "welcome" div element, as discussed in the following section.

Adding, removing and replacing elements

You know that a Web page is made up of a tree of DOM nodes. For example, a paragraph containing a string of text and an image is represented by a p element node with two child nodes: a text node, and an img element node.

This means that, in order to alter the contents of an element that itself contains child elements, you need to be able to add and remove those child elements. Here's how to do it.

Adding elements

To add an element to the DOM tree, you first need to create the element. You do this using the document.createElement() method, passing in the tag name of the element you want to create:


elementVar = document.createElement( tagName );

Once you've created your element node, you can then add it as a child to an existing node in the document using element.appendChild():


element.appendChild( elementVar );

The following example adds a horizontal rule (hr) element after the paragraph inside our "welcome" div:


var welcome = document.getElementById( "welcome" );
var horizRule = document.createElement( "hr" );
welcome.appendChild( horizRule );

What if you wanted to insert the horizontal rule before the paragraph? You can use element.insertBefore() to insert an element before a specified child node, rather than at the end of the list of child nodes. insertBefore() takes two parameters: the element to insert, and the child node to insert the element before.

So to insert the horizontal rule before the paragraph, first create the hr element, then retrieve the paragraph node, then call the div element's insertBefore() method, as follows:


var welcome = document.getElementById( "welcome" );
var horizRule = document.createElement( "hr" );
var paragraph = welcome.firstChild;
welcome.insertBefore( horizRule, paragraph );

Removing elements

To remove an element from the page, first retrieve the element using, for example, document.getElementById() or element.firstChild. Once you have the element, you can then remove it from its parent element by calling parent.removeChild(), passing in the element to remove:


removedElement = element.removeChild( elementToRemove );

removeChild() removes the element from the DOM tree and returns it. You can just ignore the returned object, or store it for later use if required.

For example, here's how to remove the hr element that you just added after your paragraph:


var welcome = document.getElementById( "welcome" );
var horizRule = welcome.lastChild;
welcome.removeChild( horizRule );

You can use appendChild() and removeChild() to add or remove any type of DOM node, not just elements — provided, of course, that the node in question can be added to or removed from the parent element.

Replacing elements

You can also replace one element in the DOM tree with another. For example, you could replace the hr element in the previous example with a new p element:


var welcome = document.getElementById( "welcome" );
var horizRule = welcome.lastChild;
welcome.removeChild( horizRule );
var newPara = document.createElement( "p" );
newPara.appendChild( document.createTextNode( "Feel free to have a browse." ) );
welcome.appendChild( newPara );

Note the use of a new method, document.createTextNode(). This works much like document.createElement(), but it returns a text node containing the supplied text.

Also notice that you can add child nodes to a node with appendChild(), even though the parent node isn't yet part of the main document's DOM tree. For example, in the above code the text node is added to the newPara element before newPara is added to the "welcome" div element.

Although the above approach works, there's a cleaner way to replace an element, and that is to use element.replaceChild(). This method takes the new child to use, followed by the child to replace, and returns the replaced child (which you can ignore if you don't need it). So the above code can be rewritten as:


var welcome = document.getElementById( "welcome" );
var horizRule = welcome.lastChild;
var newPara = document.createElement( "p" );
newPara.appendChild( document.createTextNode( "Feel free to have a browse." ) );
welcome.replaceChild( newPara, horizRule );

Moving elements around

Now that you know how to add, remove, and replace elements, you can easily move elements from one part of the DOM tree to another. Here's a simple example. Imagine that your page contains the following list:


<ul>
  <li id="widget1"><a href="superwidget.html">SuperWidget</a></li>
  <li id="widget2"><a href="megawidget.html">MegaWidget</a></li>
  <li id="widget3"><a href="wonderwidget.html">WonderWidget</a></li>
</ul>

To move the SuperWidget list item to the end of the list, you could use:


var superWidget = document.getElementById( "widget1" );
var ul = superWidget.parentNode;
ul.appendChild( superWidget );

Notice that you don't need to remove the SuperWidget list item from the list before you then append it. When you use appendChild(), insertBefore(), or replaceChild() to add an element that already exists in the page, the element is automatically removed from its old position in the page. In other words, the element is moved rather than copied.

Changing attributes

So far you've looked at changing the contents of elements: you've altered the value of a text node inside an element, and manipulated the child nodes of an element. How about changing the attributes of an element?

Changing an attribute's value

In the last tutorial you learned how to retrieve an element's attribute node using getAttributeNode(). Once you have the attribute, you can change its value property. This immediately updates the attribute's value in the page. Say you have a photo of your cat in your Web page:


<div>
  <img id="photo" src="cat.jpg" alt="My cat" />
</div>

To replace the cat photo with a dog photo, updating both the src and alt attributes, you could write:


var photo = document.getElementById( "photo" );
var photoSrc = photo.getAttributeNode( "src" );
var photoAlt = photo.getAttributeNode( "alt" );
photoSrc.value = "dog.jpg";
photoAlt.value = "My dog";

Adding and removing attribute nodes

To add a new attribute node to an element, first create the attribute node by calling document.createAttribute(), passing in the name of the attribute to create. The method returns the attribute node:


attributeNode = document.createAttribute( attributeName ); 

Then you can assign a value to your new attribute node's value property:


attributeNode.value = value; 

Finally, add the attribute to the element by calling element.setAttributeNode():


element.setAttributeNode( attributeNode ); 

If an attribute with the same name already exists for the element, it is replaced by the new attribute node. The old attribute node is then returned by element.setAttributeNode().

Here's an example that adds the attribute width="50" to your "photo" img element:


var photo = document.getElementById( "photo" );
var widthAttr = document.createAttribute( "width" );
widthAttr.value = 50;
photo.setAttributeNode( widthAttr );

To remove an attribute node, call element.removeAttributeNode(), passing in the node to remove:


var photo = document.getElementById( "photo" );
var widthAttr = photo.getAttributeNode( "width" );
photo.removeAttributeNode( widthAttr );

removeAttributeNode() returns the removed attribute node, which you can store for later, or ignore.

Attribute shortcuts

If you're thinking that all of this retrieving, creating, adding, and removing of attribute nodes is somewhat tedious, you'd be right. Fortunately the DOM provides a couple of shortcut methods to make life easier. These methods work directly with element objects, rather than dealing with attribute nodes:

element.setAttribute( name, value )
Adds an attribute with a name of name and a value of value to the element. If an attribute with the same name already exists in the element, its value is changed to value.
element.removeAttribute( name )
Removes the attribute called name from the element.

For example:


var photo = document.getElementById( "photo" );
photo.setAttribute( "width", 50 );
photo.removeAttribute( "width" );

Most of the time you'll probably want to use setAttribute() and removeAttribute() rather than the node-based approach. They're quick and easy, and you rarely need to work at the node level anyway.

Now that you've read this tutorial, you have pretty much all you need to create an entire Web page from scratch using nothing but DOM objects. You also have the knowledge to manipulate an existing Web page using the DOM, including changing element content, adding and removing elements, moving elements around, and altering element attributes.

Follow Elated

Related articles

Responses to this article

2 responses (oldest first):

01-Feb-10 20:27
I am a non-experienced coder. I can read tutorials, kind of understand, copy and paste code, and alter it.. and in many cases realise what Im doing

I have seen other demo's of what your tute is about, and im looking for a solution for the following variation or your example:

I want to be able to change elements (such as clicking on an image 'red dot' and it changes to a 'green dot', then clicking on it again replaces with the initial 'red dot' and so on..). The difference being that I want this to effect the web page overall, for every viewer, not just current viewers browser. And i dont want the image to reset upon a page reload. I want ANY person to be able to change the image from green to red or red to green and i want the change to occur on any visitors browser, and remain that way, until the dot is clicked again (by anyone).

Is this possible and is there an easy/ basic way to implement this?
02-Feb-10 01:47
Hi leanne, welcome to the forums.

If you want the button change to be visible to anyone viewing the site, you're going to need to do some server-side coding I think (e.g. PHP), possibly combined with JavaScript in the browser to register the click and change the button.

A basic approach might be:

1. A PHP script (call it page.php) displays the page to the viewer containing (for example) a red button.

2. A viewer clicks the red button.

3. The button has an "onclick" JavaScript event handler which changes the button to green, and also sends an XML (Ajax) request to a server-side PHP script - something like button-click.php?newcolour=green .

4. The PHP script stores the new button state (green) in a text file or database.

5. When another person visits the page, the page.php script reads the current button state from the text file, and displays the appropriate button image in the page (green in this case).

As an alternative to step 5, you could use JavaScript to poll a PHP script every, say, 10 seconds to update the button image without having to reload the page. Again, you could do this with an XML request (Ajax).

I'd recommend using something like jQuery to do the XML requests - much easier than coding from scratch: http://jquery.com/

Does that help?

Cheers,
Matt

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page