tags:

views:

45

answers:

2

I have several vertically stacks divs and I want to have a div appear when I click a button within each of these divs. The div that I want to appear will be the exact same for each appearance with the exception of an id associating it with the outer div. How do I do this in Javascript?

I assume I should use the createElement() within Javascript, but how do I append it to the end of a specific element. Also, when creating an element, I have to hardcode the html in the Javascript file. Is there anyway to leave the element within the html design file. I want to seperate design from code as much as possible.

+2  A: 

Clone Node

var clone = myDiv.cloneNode();

Example (live demo):

HTML

<div>
    <input type="button" onclick="functionClone(this);" value="Dolly"/>
    <input type="button" onclick="functionClone(this);" value="Dolly_1"/>
</div>

Javascript:

functionClone = function(subject){
    var clonenode = subject.cloneNode(true);
    subject.value = subject.value + '\'s been cloned!';
    subject.disabled = true;
    insertElementAfter(subject, clonenode);
}     

insertElementAfter = function(subject, newElement){
    subject.parentNode.insertBefore(newElement,subject.nextSibling);
}
Michael Robinson
Thanks for the code and the neat live demo! When I click the "Dolly" button, I want to append a div below the "Dolly" button.
Charlie
Updated my answer
Michael Robinson
A: 

To append an element below your div use this:

subject.parentNode.appendChild(clonenode)
iKid