How can i download some of content instead of all content of web page when i click on Save as HTML in browser

Viewed 110

When I click on save as HTML button its Download all content of web page but i have require to Download some for specific content from all content.

function download(filename, contents) {
  const anchor = document.createElement('a');
  anchor.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(contents));
  anchor.setAttribute('download', filename);
  anchor.style.display = 'none';
  document.body.appendChild(anchor);
  anchor.click();
  document.body.removeChild(anchor);
}

const btn = document.querySelector('#save-btn');

btn.addEventListener('click', (evt) => {
  const container = document.createElement('div');
  const html = document.createElement('html');
  html.innerHTML = document.documentElement.innerHTML;
  container.appendChild(html);
  download('index.html', container.innerHTML);
});
<p>Hello World</p>
<button id="save-btn">Save as HTML</button>
<div>
  <p>Hello World-1</p>
  <p>Hello World-2</p>
  <p>Hello World-3</p>
</div>

On above HTML Example, when i click on save as HTML Button i have download some of portion of file like download div content instead of all content. in sort when I open download file it display only this content:

<div>
  <p>Hello World-1</p>
  <p>Hello World-2</p>
  <p>Hello World-3</p>
</div>
1 Answers

To only download the HTML of a specific element, change the logic to select that element instead of the entire body, like this:

document.querySelector('#save-btn').addEventListener('click', e => {
  e.preventDefault();
  let html = document.querySelector('div').outerHTML; // update this selector in your local version    
  download('index.html', html);
});

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);
  element.style.display = 'none';
  document.body.appendChild(element);
  
  element.click();
  document.body.removeChild(element);
}

Working example

Related