0

I have a node like below

<body id="hello" dir="auto" style="margin-top:0;margin-bottom:0;color:red" bgcolor="green";></body>

i want to extract id="hello" dir="auto" style="margin-top:0;margin-bottom:0;color:red" bgcolor="green"; from the body tag and to apply the same to another tag say DIV. How can this be possible.

Veena Sujith
  • 175
  • 1
  • 5
  • 16
  • [This answer](http://stackoverflow.com/a/6753523/218196) doesn't use jQuery for the important part. This one might also be relevant: http://stackoverflow.com/q/2715447/218196 – Felix Kling Jul 17 '14 at 07:07
  • Not only Style, i want to copy all the data, like id, dir, bgColor – Veena Sujith Jul 17 '14 at 07:20
  • I just noticed that the other question is too jQueryish unfortunately (unless you are using jQuery anyways). It's very straightforward to adept it for plain JS though. – Felix Kling Jul 17 '14 at 07:28
  • 1
    Better duplicate: http://stackoverflow.com/a/20766701/218196 – Felix Kling Jul 17 '14 at 07:32

1 Answers1

1

Just do something like this, no jQuery needed.

var newDiv = document.body.cloneNode();
document.body.appendChild(newDiv);
newDiv.outerHTML = newDiv.outerHTML.replace(/body/g,"div");

fiddle

Or even a cleaner way seen here

var newDiv = document.createElement('div'),
    body = document.body;

for (var i = body.attributes.length; i--;) {
    var attr = body.attributes.item(i);
    newDiv.setAttribute(attr.nodeName, attr.nodeValue);
}

It copy's all the attributes from an element, in this case body, to the new div.

Community
  • 1
  • 1
A1rPun
  • 16,287
  • 7
  • 57
  • 90
  • is there anything to change it directly with node, since changing outer html from the document will not be possible many times. – Veena Sujith Jul 17 '14 at 07:19
  • Yes that is possible, look at the answers in the links by @FelixKling. I'll add a snippet to my answer. – A1rPun Jul 17 '14 at 07:42
  • Got it... i was expecting something to avoid looping through the attributes. So only was searching for shortcut. If it was copy only style, then easily using node.style.cssText we can take. Similarly without looping through the attributes any short cut is there or not i was checking. Thanks for the update. – Veena Sujith Jul 17 '14 at 08:37