Javascript: insertBefore()

Posted by jcargoo | Sunday, October 26, 2008
| 0Delicious Twitter Reddit Digg Loading...

The function inserts an element either at the end of the document or after the specified element.

The following example illustrates the utility of this function. We will add list elements without reloading the page. Of course it should undergo some smart enhancements (manage adding black element…) to be perfect. Now this is not the purpose as this just a simple example.

The body element will contain the following code

Add a new element into the element <ul>
Fill in the element you want to add in the list
<input name="addedElement" id="addedElement" type="text" value="" />
<input type="button" value="Add" name="submit"
onClick="javascript:addNewElement()" />
<div id="msg"></div>

<ul id="addedList">
  • msg : displays two kinds of warnings (either the element was perfectly added or not);
  • addedList: Will simply display the list of new added element.

Here is the JavaScript code well commented:

<script language="javascript">
function addNewElement(){
// Get the entred value into the input text field
var element=document.getElementById('addedElement').value;
// Show an error message if the field is empty;
document.getElementById('msg').innerHTML = "Error! Insert a non empty element";
// The containter of <ul id="addedList"> element that will contains the new elements
var container = document.getElementById('addedList');
// Create a new <li> element to insert into <ul id="addedList">
var added_element = document.createElement('li');
added_element.innerHTML = element;
container.insertBefore(added_element, container.firstChild);
// Show a message if the element has been added successfully;
document.getElementById('msg').innerHTML = "Elemend added!";
// Clean input field after adding an element

Now you have just to style your file. All HTML (JS, CSS…) file is enclosed here.


How to encourage this blog if you like it:
  • Promote our sponsors;
  • Add any kind of comment or critic;
  • Ask me directly by email if you prefer.
Just do something like that, and I will have the huge pleasure to continue posting the best of the creativity I have.

Share this post ?

Digg Reddit Stumble Delicious Technorati Twitter Facebook

0 Previous Comments