Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - Copy the content of a div into another div

I have two divs on my website. They both share the same css properties, but one of them holds 24 other divs. I want all of these 24 divs to be copied into the other div. This is how it looks like:

<div id="mydiv1">
    <div id="div1">
    </div>
    </div id="div2>
    </div>
    //and all the way up to div 24.
</div>

<div id="mydiv2">
</div>

I want all of the 24 divs within mydiv1 to be copied into mydiv2 when the page loads.

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Firstly we are assigning divs into variables (optional)

var firstDivContent = document.getElementById('mydiv1');
var secondDivContent = document.getElementById('mydiv2');

Now just assign mydiv1's content to mydiv2.

secondDivContent.innerHTML = firstDivContent.innerHTML;

DEMO http://jsfiddle.net/GCn8j/

COMPLETE CODE

<html>
<head>
  <script type="text/javascript">
    function copyDiv(){
      var firstDivContent = document.getElementById('mydiv1');
      var secondDivContent = document.getElementById('mydiv2');
      secondDivContent.innerHTML = firstDivContent.innerHTML;
    }
  </script>
</head>
<body onload="copyDiv();">
  <div id="mydiv1">
      <div id="div1">
      </div>
      <div id="div2">
      </div>
  </div>

  <div id="mydiv2">
  </div>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...