Dave
Dave

Reputation: 129

Search and Replace within DOM node in JavaScript

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.

Upvotes: 0

Views: 86

Answers (1)

Arie Xiao
Arie Xiao

Reputation: 14082

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

Upvotes: 1

Related Questions