skip to Main Content

I am building a web app and I need to copy an HTML div and everything inside it into a new tab. I am writing this code in JavaScript. So far I have been working on creating a blob and then creating a file to download. This approach copies all the HTML code I need BUT it does not copy the text that has been inputted into any text fields. As I understand, the problem is that the entered text is not part of the HTML code so it cannot be copied. However I cannot find another approach to this, please assist. Thank you

2

Answers


  1. You can use Element.setAttribute() on those elements before serializing your DOM tree. For example:

    input.setAttribute("value", input.value)
    

    This will copy the mutable value (not serializable) to the attribute (which is serializable).


    Here’s a snippet demonstration:

    const input = document.querySelector('input');
    
    console.log('initial:', input.outerHTML);
    
    input.value = 'hello world';
    console.log('before:', input.outerHTML);
    
    input.setAttribute('value', input.value);
    console.log('after:', input.outerHTML);
    <input type="text">
    Login or Signup to reply.
  2. (Inspired by comment by @vanowm)

    First, copy the html (say inside a DIV)

    Then you’ll need loop through all input fields and read their value so you can apply them.

    So the code is like this (amend to suit your further needs):

    <div id=container><html>
    <input type=text name=text1 id="text1">
    <br><input type=text name=text2 id="text2">
    </html></div>
    
    <textarea id=target style="width:100%;height:200px;"></textarea>
    
    <input type=button name=go onclick="trigger();" value="Parse">
    
    <script>
    function trigger(){
    target0=document.getElementById('container').innerHTML;
    
    text1= document.getElementById("text1").value;
    text2= document.getElementById("text2").value;
    
    target0=target0.replace('id="text1"', 'id="text1" value="' + text1 + '"');
    target0=target0.replace('id="text2"', 'id="text2" value="' + text2 + '"');
    
    document.getElementById("target").innerHTML=target0;
    
    }
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search