Search code examples
javascriptcopyhandlebars.js

Copy divs with certain id's to targets with related id's


How do I copy the content from all divs with a certain class or a certain beginning of an id to a bunch of divs with related id's? The examples I found didn't go through multiple copies. I have a solution that is working ok but instead of calling each copy with the id I would like to make the logic better.

Here's what I have now.

HTML (handlebars template)

<!-- the id comes from handlebar content. There are many like this -->

<pre><code id="target-example-01" class='language-markup'></code></pre>

<!-- this content is put to place once handlebars has rendered the page  -->
<div id="code-examples" style="display: none;">
  <div class='code-example' id="source-example-01">
    this is my a code example... there are many like me...
  </div>
</div>

Javascript

var source = document.getElementById('source-example-01').innerHTML;
var target = document.getElementById('target-example-01');
if (target) target.innerHTML=source;

This works ok but I have 100 examples so I wouldn't like to have 300 lines of code to manually maintain just to copy the content. How do I go through all the divs with "code-example" class and copy their content to divs with a matching id. All the source divs will have the id="source-(example-identifier)" and all the target divs will have the id="target-(example-identifier)". I guess the class wouldn't be needed if the code would go through all items with the id beginning with "source-"


Solution

  • How do I go through all the divs with "code-example" class and copy their content to divs with a matching id

    Assuming that index of code-example elements is same as that of targets, then try

    var allCodeExamples = document.getElementsByClassName( "code-example" );
    for ( var counter = 0; counter < allCodeExamples.length ; counter++ )
    {
       var index = ("0" + counter).slice( -2 );
       var target = document.getElementById( "target-example-" + index );
       target.innerHTML = allCodeExamples[counter].innerHTML;
    }