Insert an element before a HTML element using DOM
by Vijay[ Edit ] 2009-03-10 12:43:09
sometimes we may want to add an HTML element dynamically before an element, for that there is a DOM function called as insertBefore().
This function is very useful when we want to place/add an element between two elements or specifically before any element.
Here is an example,
<html>
<body>
<div>
<span id="firstSpan">This is first Span</span>
<span id="childSpan">This is second Span</span>
</div>
<script type="text/javascript">
// create an empty element node
// without an ID, any attributes, or any content
var sp1 = document.createElement("select");
// give it an id attribute called 'newSpan'
sp1.setAttribute("id", "newSpan");
// create some content for the newly created element.
var sp1_content = document.createElement("option");
sp1_content.setAttribute("value","This is a new span element. ");
// apply that content to the new element
sp1.appendChild(sp1_content);
var sp2 = document.getElementById("childSpan");
var parentDiv = sp2.parentNode;
// insert the new element into the DOM before sp2
parentDiv.insertBefore(sp1, sp2);
</script>
</body>
</html>
In the above example a new select element will be added between the first two span.