Reputation: 3581
HTML page:
FIRST ELEMENT
The onclick function of FIRST ELEMENT (which is < h1 >) has the following function:
function insert(event)
{
elem = document.getElementById("first");
element = document.createElement("div");
element2 = document.createElement("a");
element2.href = "www.google.com";
element2.innerHTML = "GOOGLE" + n;
element.appendChild(element2);
//element.innerHTML = "text content";
element.style.position = "relative";
element.style.backgroundColor = "yellow";
element.style.left = "10px";
element.style.top = "30px";
elem.appendChild(element);
//document.body.appendChild(element);
event.target.appendChild(element);
n++;
}
on clicking the 'FIRST ELEMENT' two times the output is:
FIRST ELEMENT
GOOGLE1
GOOGLE2
but I want the output to be:
FIRST ELEMENT
GOOGLE2
GOOGLE1
How can I achieve this?
Upvotes: 0
Views: 75
Reputation: 710
You can use insertBefore to rearrange the order of an elements children. Here is what you want:
var n = 1;
function myfunc(event)
{
elem = document.getElementById("first");
element = document.createElement("div");
element2 = document.createElement("a");
element2.href = "www.google.com";
element2.innerHTML = "GOOGLE" + n;
element.appendChild(element2);
element.style.position = "relative";
element.style.backgroundColor = "yellow";
element.style.left = "10px";
element.style.top = "30px";
elem.appendChild(element);
children = elem.children;
if(typeof(children) != "undefined" && children.length > 1){
num = children.length - 1;
elem.insertBefore(children[num], children[1]);
}
n++;
}
Link to working sample: http://jsfiddle.net/szNcT/
Upvotes: 1