Link to home
Start Free TrialLog in
Avatar of lawrenced1
lawrenced1Flag for United States of America

asked on

How can I copy an element by looping thru it's attributes?

How can I copy an element by looping thru the element's attributes and then using createElement() to apply those attributes to the new element?

I have a script that reads in an element and then deletes the element off the page.  In order to have an "undo" method, I was going to store the elements attributes in an array as an object parameter.  Then when the undo method is called, I was going to rebuild the element by looping thru the stored attributes.

Example trying to copy an element:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
      <title>CopyElement</title>
      <script type="text/javascript">
            function copyMe(e) {
                  eAttributes = e.attributes;
                  var newElement = document.createElement(e.nodeName);
                  for (i=0;i<eAttributes.length; i++) {
                        if (eAttributes[i].specified)
                              newElement.setAttribute(eAttributes[i].nodeName, eAttributes[i].nodeValue);
                  }
                  document.getElementById('placeHolder').appendChild(newElement);

                  if (e.innerHTML) {
                        document.getElementById('placeHolder').firstChild.innerHTML = e.innerHTML;
                  }
            }
      </script>
</head>
<body>
<input type="button" name="testButton" id="testButton" value="Copy Me!" onclick="copyMe(this);">
<hr>
<div id="placeHolder"></div>
</body>
</html>


The above code works fine in Firefox but IE doesn't appear to be applying the value attribute or the onclick event, and possibly others?  

Anyone have suggestions on how I can do this?
ASKER CERTIFIED SOLUTION
Avatar of Pravin Asar
Pravin Asar
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lawrenced1

ASKER

pravinasar ,

Thanks, that got me what I needed.