0

I'm creating a form and would like to be able to duplicate certain DIVs as needed using javascript. However, I need to replace multiple instances of a certain piece of text. Something like this with the comment replaced by functional code:

<body>

   <div id="duplicate">
      <p>Section_1 of form</p>
      <a href="javascript:add_section()">Add A Section</a>
   </div>

   <script type="text/javascript">
   <!--
      var num_sections = 1;
      function add_section()
      {

         var orig_div=document.getElementById("duplicate")
         var copy_div=orig_div.cloneNode(true);

         //Change every "Section_1" in copy_div to "Section_"+num_sections

         footer = document.getElementById("footer");
         document.body.insertBefore(copy_div,footer);

      }

   //-->
   </script>

   <div id="footer"></div>

</body>

Using JavaScript, what is an elegant way to replace every instance of Section_1 when these instances are in every input tag within the section ?

I'm working within the confines of a CMS so I can't implement it using a more powerful processing language.

1 Answer 1

1

You can call getElementsByTagName on a DOM node to fetch some elements group identified by the tag.

var num_sections = 1;
window.add_section = function() {
    var orig_div=document.getElementById("duplicate")
    var copy_div=orig_div.cloneNode(true);

    //Change every "Section_1" in copy_div to "Section_"+num_sections
    num_sections++;
    var p = copy_div.getElementsByTagName('p')[0];
    p.innerHTML = p.innerHTML.replace('Section_1', 'Section_' + num_sections);

    var footer = document.getElementById("footer");
    document.body.insertBefore(copy_div,footer);
};

Here's jsFiddle

Sign up to request clarification or add additional context in comments.

4 Comments

Wrap a for loop around the replace line and this is what I was looking for. I will have to repeat that section of code for each tag type but, fortunately in this case, that won't be a problem.
Thanks also for the link to jsFiddle. Looks like a useful tool.
@Dave Maybe you can use p.innerHTML.replace(/Section_1/g, 'Section_' + num_sections) to get rid of the loop as you mentioned.
That would make changes to instances in the same tag only correct? The changes actually need to be made in the name attribute of each input field. I should have had my sample code reflect that better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.