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
:
Here is the JavaScript code well commented:
Now you have just to style your file. All HTML (JS, CSS…) file is enclosed here.
Results:


<center>
<h2>
Add a new element into the element <ul>
</h2>
</center>
Fill in the element you want to add in the list
<br>
<br>
<input name="addedElement" id="addedElement" type="text" value="" />
<input type="button" value="Add" name="submit"
onClick="javascript:addNewElement()" />
<br>
<p>LIST</p>
<div id="msg"></div>
<ul id="addedList">
</ul>
- 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;
if(element==""){
// Show an error message if the field is empty;
document.getElementById('msg').style.display="block";
document.getElementById('msg').style.backgroundColor='#FFC1C1';
document.getElementById('msg').innerHTML = "Error! Insert a non empty element";
}else{
// 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').style.display="block";
document.getElementById('msg').style.backgroundColor='#66CDAA';
document.getElementById('msg').innerHTML = "Elemend added!";
// Clean input field after adding an element
document.getElementById('addedElement').value="";
}
}
</script>
Now you have just to style your file. All HTML (JS, CSS…) file is enclosed here.
Results:



- Promote our sponsors;
- Add any kind of comment or critic;
- Ask me directly by email if you prefer.






