简体   繁体   中英

Is it possible to save an html element with child elements as JS variable which you can dynamically append to the DOM?

I have this form snippet

<div id="form-container" class="row">
       <select style="width:250px;" name="drug_pack_size" id="drug_pack_size" class="form-control">
         <option value="">Selling Unit</option>
         <option value="Ampoule">Ampoule</option>
       </select>
       <span class="d-flex">
         <p class="mx-3">contains</p>
         <input type="text" class="form-control">
       </span>
       <span class="d-flex">
         <p class="mx-3">for</p>
         <input type="text" class="form-control">
         <p class="mx-3">GHC</p>
       </span>
     </div> 

Is it possible to do something like this

const form = document.querySelector('#form-element').content

Such that you can append it repeatedly and dynamically with JS code, without writing everything from the JS Backend

Yes, it is possible. Please try

 var x = document.getElementById("form-container").outerHTML;
 window.alert(x);

After this capture, if you want to repeatedly add same parent Element, then include variable(s) to increment the id and/or name of the parent and child elements to prevent duplication. For example, id="form-container1" , id="form-container2" , id="form-container3" , and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM