Australian Made and Owned

Adding, Removing and Editing Elements Dynamically using JavaScript

Using Javascript to Dynamically Add and Remove Elements While working myLookAgain (the second attempt), I’ve had to use a little bit more AJAX through JavaScript. One of the reasons was that I needed to allow users to add as many ‘pieces’ to each look and delete them if they want - preferably without reloading.

In JavaScript terms, I needed to be able to add (or create) and remove (or delete) elements, within another element, the form. After a little bit of research on the internet, I had what I needed to do just that. See a basic example of javascript dynamically adding and removing elements… Here’s how to do it:

To begin with, here’s the commented JavaScript code for adding an element using the DOM in JavaScript

function appendElement(containerId, newElementId, newElementContent) {
	//First, we need to create a new DIV element
	var newElement=document.createElement("div");
	//New we will give it the specified ID so we can manage it later if necessary
	newElement.setAttribute("id", newElementId);
	//Insert the HTML content into the new element
	newElement.innerHTML=newElementContent;

	//Get a reference to the element that will contain the new element
	var container = document.getElementById(containerId);
	//Now we just need to insert our new element into the containing element
	container.appendChild(newElement, container);
}

And here’s the commented JavaScript code for a function to remove elements:

	function removeElement(parentId, elementId) {
	//Get a reference to the element containgint the element we are removing
	var parentElement = document.getElementById(parentId);
	//Get a reference to the element we are removing
	var childElement = document.getElementById(elementId);
	//remove the
	parentElement.removeChild(childElement);
}

And that’s it. Of course, this by itself isn’t going to do much. Though with a little bit of imagination, these functions can help you improve the usability or usefulness of your website.



Did you like this post?
Email Send to a friend Add to Technorati Favorites

AddThis Social Bookmark Button
AddThis Feed Button

Leave a comment

3 Comments

  1. Web Designer Group

    Nice post. Thanks for such useful work.

    February 20, 2008 @ 4:03 pm

  2. Website Design Perth

    If you haven’t done so already, check out jquery.js (and the endless plug-ins available). We all know Flash ain’t great for SEO so if you need to pep up your website interface then unobtrusive javascript could be the answer…

    June 6, 2008 @ 12:25 pm

  3. techvech

    hii
    any ideas how can i save these to the databases when i click on save..
    if there are multiple instances of the same fields

    July 7, 2009 @ 6:44 pm

RSS feed for comments on this post. TrackBack URL