skip to Main Content

I have two HTML pages.

Index.html

<div id="source">
    Contenido de Usuario
</div>

<input type="button" id="export" value="Export Data">

Users.html

<div id="target">
</div>

How to display the content of the source <div> element in Index.html inside the target <div> element in Users.html with JavaScript?

2

Answers


  1. Use the fetch() API.

    Index.html

    <div id="source">
        Contenido de Usuario
    </div>
    

    Users.html

    <div id="target">
        <!-- content will be inserted here -->
    </div>
    
    <script>
        window.onload = function() {
            fetch("Index.html")
                .then(response => {
                    if (!response.ok) {
                        throw new Error("Error with response.");
                    }
                    return response.text();
                })
                .then(html => {
                    let parser = new DOMParser();
                    let doc = parser.parseFromString(html, "text/html");
                    let sourceContent = doc.getElementById("source").textContent;
                    document.getElementById("target").textContent = sourceContent;
                })
                .catch(error => {
                    console.error("Error fetching content:", error);
                });
        };
    </script>
    

    You may need to sanitize the HTML content first as well, just to make sure it’s safe to append using, for example, DOMPurify.

    Login or Signup to reply.
  2. You make no mention of the size of this source or what kind of data it is… both of which are very important in making an informed decision.

    Anyway, assuming the size is less than 2.5MB and the data is plain text with nothing special in there, I guess you can…

    In Index.html

    <body onload="sessionStorage.setItem('source',source.textContent);">
    

    In Users.html

    <body onload="target.textContent=sessionStorage.getItem('source');">
    

    NB: Untested pseudo-code suggestion.

    Update: So an hour later you decide to introduce a button into the equation eh… not very smart!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search