HTML button to save div content using javascript

22,101

Solution 1

Close, you need innerHTML & trigger the click too:

function download(){
    var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "export.html";
    a.href = "data:text/html," + document.getElementById("content").innerHTML; // Grab the HTML
    a.click(); // Trigger a click on the element
}

Working Fiddle

Solution 2

In your jsfiddle Java Script is configured to onLoad, which is why download() is not being invoked. Change it to No-Wrap, then you will be able invoke download() on onClick of the button.

update download() as

function download(){
    var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "export.html";
    a.href = "data:text/html," + document.getElementById("content").innerHTML;
     a.click();

}

Solution 3

I agree with RGraham. However, if you use jQuery you can do it like this.

<div id="content">
    <h1>Hello world</h1>
    <i>Hi everybody</i>
</div>
<button class="download">Download</button>

<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
    $('.download').on('click', function(){
       $('<a />').attr({
              download: 'export.html', 
              href: "data:text/html," + $('#content').html() 
       })[0].click()
    });
</script>
Share:
22,101

Related videos on Youtube

nosmoke
Author by

nosmoke

Updated on July 09, 2022

Comments

  • nosmoke
    nosmoke almost 2 years

    I need to save content of div using pure javascript. I just edited one fiddle but I can't make it works :(

    jsfiddle

    <div id="content">
    <h1>Hello world</h1>
    <i>Hi everybody</i>
    

    Download

    function download(){
        var a = document.body.appendChild(
            document.createElement("a")
        );
        a.download = "export.html";
        a.href = "data:text/html," + document.getElementById("content");
    }
    
  • nosmoke
    nosmoke about 9 years
    Works great! Thank you soooo much fr your help! :) Can I add a charset to the data?
  • CodingIntrigue
    CodingIntrigue about 9 years
    Sure, just add ;charset= after the text/html bit
  • Walker Boh
    Walker Boh about 9 years
    Odd, every time I try that on jsfiddle, it doesn't recognize the function
  • Faraj Farook
    Faraj Farook about 9 years
    sometimes jfiddle renders the output incorrectly. Try to create a new jfiddle and paste the code n try.
  • CodingIntrigue
    CodingIntrigue over 7 years
    @Cutter For IE, you should look at window.navigator.msSaveBlob. For Safari, you might need to have the user click on the element manually