How to change innerHTML content, e.g. (input field names, identifiers, onclick)

I want to copy the entire contents of a div to another div, but before copying, I need to change all the input field names and identifiers. See code below.

 <div id="first_div">
    <input type="text" name="firstname" id="firstname">
    <select name="marital_status" id="marital_status">
        <option value="1" selected='selected'>Select</option>
        <option value="2">Single</option>
        <option value="3">Married</option>
   </select>
 </div>
 <div id="second_div">
 </div> 

Now I want to copy the contents of first_div to second_div, but before copying I need to change the name of the firstname field to last_name, how can I do this?

+4
source share
4 answers

As I see, you noted jQuery in the question, you can use the jQuery cloning method for quick launch: https://api.jquery.com/clone/

var clone = $("#first_div").clone();

then modifying the innerHTML clone this way

clone.find("#firstname").attr("id", "lastname"); // modifying div id
// do the same for every element you want to modify id, etc
//then finally append it to the second_div
$("#second_div").html(clone.html());
+6
source

JavaScript:

var clone = document.getElementById('first_div').cloneNode(true);
clone.querySelector('#firstname').id = 'lastname';

document.getElementById('second_div').innerHTML = clone.innerHTML;

jQuery, , , .

+1

Using pure javaScript

 var fdiv = document.getElementById("first_div");
 var clnNode = fdiv.cloneNode(true);

 var clnInput = clnNode.querySelector('#firstname');
 clnInput.setAttribute('id', 'lastname')

 var secDiv = document.getElementById('second_div')
 secDiv.innerHTML = clnNode.innerHTML;
0
source

Just copy the internal html and replace id:

var html = document.getElementById('first_div').innerHTML;
html = html.replace(/firstname/g, 'last_name');
document.getElementById('second_div').innerHTML = html;
<div id="first_div">
  <input type="text" name="firstname" id="firstname">
  <select name="marital_status" id="marital_status">
    <option value="1" selected='selected'>Select</option>
    <option value="2">Single</option>
    <option value="3">Married</option>
  </select>
</div>
<div id="second_div">
</div>
Run code
0
source

Source: https://habr.com/ru/post/1608125/


All Articles