salah
salah

Reputation: 1

how can i copy a div from external html file and save it into other html file

I want to copy an HTML div from external file and save it into other html file by clicking a button and using JavaScript:

<html lang="en">
  <head>
    <title>Document 1</title>
  </head>
  <body>
    <div class="container1">
      <p>text 1</p>
    </div>

  </body>
</html>
    
<html lang="en">
  <head>
    <title>Document 2</title>
  </head>
  <body>
    <div class="container2">
      <p>text 2</p>
    </div>
    <button>Click here</button>
  </body>
</html>

Upvotes: 0

Views: 614

Answers (2)

kol
kol

Reputation: 28698

Using vanilla JavaScript:

<!-- a.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Page A</title>
</head>
<body>
  <div id="target"></div>
  <button onclick="loadElement('b.html', 'div#y', 'div#target')">Copy div#y from b.html</button>
  <script>
    async function loadElement(sourceFileName, sourceSelector, targetSelector) {
      // Load the whole <body> of the source HTML file
      const response = await fetch(sourceFileName);
      const text = await response.text();
      const i1 = text.indexOf("<body>");
      const i2 = text.indexOf("</body>");
      const bodyHTML = text.substring(i1 + "<body>".length, i2);

      // Add it to the target element
      const targetElement = document.body.querySelector(targetSelector);
      targetElement.innerHTML = bodyHTML;

      // Keep only the source element
      const sourceElement = targetElement.querySelector(sourceSelector);
      targetElement.innerHTML = "";
      targetElement.append(sourceElement);
    }
  </script>
</body>
</html>

The file to load the div from:

<!-- b.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Page B</title>
</head>
<body>
    <div>
        <div>
            <div id="x">Hello from b.html div#x!</div>
            <div id="y">Hello from b.html div#y!</div>
        </div>
        <div id="z">Hello from b.html div#z!</div>
    </div>
</body>
</html>

I tested this by starting a Python web server on Windows (py -m http.server) from the folder of these files, and opening http://localhost:8000/a.html in Chrome. Clicking on the button loads the selected div from b.html.

Upvotes: 1

Mingze Li
Mingze Li

Reputation: 390

Use jQuery can solve your problem. If you want to get div(id = "DivA") content from sampleA.html into your current html div (id= "DivB"). Assume these 2 html files are under same path.

$( "#DivB" ).load( "sampleA.html #DivA" );

Upvotes: 0

Related Questions