HTML button to save div content using javascript

梦想与她 提交于 2019-12-01 00:35:44

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

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();

}

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>

In jsfiddle, you can't run a javascript function inside of html events (like onClick) unless the javascript is contained in tags. (nevermind this)

Try this:

HTML

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

JS

var download_button = document.getElementById('download');
download_button.onclick = download;

function download(){
    var content = document.getElementById('content')
    console.log(content);
}

updated jsfiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!