How to export source content within div to text/html file

Let's say I have <div id="main"> ... Some html ...</div> and I need to take the html code whithin this div, place it inside a file and force a download of it in TXT format. How can that be done? Should I use PHP or Javascript? I rather javascript.

Answers:

Answer

You could use something like this:

Updated jsfiddle with download btn(jquery)

Initial jsfiddle with plain js and autoexecution

html

<div id="main">
    <span>Hey there</span>
</div>

html - Edit (Added a link to perform this action)

<a href="#" id="downloadLink">Download the inner html</a>

Js

function downloadInnerHtml(filename, elId, mimeType) {
    var elHtml = document.getElementById(elId).innerHTML;
    var link = document.createElement('a');
    mimeType = mimeType || 'text/plain';

    link.setAttribute('download', filename);
    link.setAttribute('href', 'data:' + mimeType  +  ';charset=utf-8,' + encodeURIComponent(elHtml));
    link.click(); 
}

var fileName =  'tags.html'; // You can use the .txt extension if you want

JS - Edit

Since you said in the comments that you are using jQuery i'll call this function from a handler, instead of calling it directly.

$('#downloadLink').click(function(){
    downloadInnerHtml(fileName, 'main','text/html');
});

You can download as a text, just remove the third argument for function, and it will take the default which is "text/plain", and add the extension .txt to the filename instead of html.

Note I edited this answer since the person who asked commented that he was looking how to make it work with a handler, he made it work, but just in case. The original code is in the jsfiddle

Answer

The intended can be achieved with a javascript method. The following function will let you add a personalized name with which you desire to download your text file.

function saveTextAsFile()
{
    //inputTextToSave--> the text area from which the text to save is
    //taken from
    var textToSave = document.getElementById("inputTextToSave").value;
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
    //inputFileNameToSaveAs-->The text field in which the user input for 
    //the desired file name is input into.
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);

    downloadLink.click();
}

function destroyClickedElement(event)
{
    document.body.removeChild(event.target);
}

The above was derived from here.

Answer

Update for Zagen function. Original will not work in IE 10-11:

function downloadInnerHtml(filename, elId, mimeType) {
    var elHtml = document.getElementById(elId).innerHTML;
    if (navigator.msSaveBlob) { // IE 10+ 
        navigator.msSaveBlob(new Blob([elHtml], { type: mimeType + ';charset=utf-8;' }), filename);
    } else {
        var link = document.createElement('a');
        mimeType = mimeType || 'text/plain';

        link.setAttribute('download', filename);
        link.setAttribute('href', 'data:' + mimeType  +  ';charset=utf-8,' + encodeURIComponent(elHtml));
        link.click(); 
    }
}
Answer

Here is my full code, I hope it can be of some help to someone in the same situation

<!-- SAVE AS HTML OR TXT FILE -->
    <script type="text/javascript">


            // Wait for the page to load first
            window.onload = function() {

              //Get a reference to the link on the page
              // with an id of "exportxt"
              var a = document.getElementById("exportxt");

              //Set code to run when the link is clicked
              // by assigning a function to "onclick"
              a.onclick = function() {

                // Your code here...


    function downloadInnerHtml(filename, elId, mimeType) {
        var elHtml = document.getElementById(elId).innerHTML;
        var link = document.createElement('a');
        mimeType = mimeType || 'text/plain';
        link.setAttribute('download', filename);
        link.setAttribute('href', 'data:' + mimeType  +  ';charset=utf-8,' + encodeURIComponent(elHtml));
        link.click(); 
    }
    var fileName =  'myexportedhtml.txt'; // You can use the .txt extension if you want
    downloadInnerHtml(fileName, 'editor','text/plain');
                //If you don't want the link to actually 
                // redirect the browser to another page, then
                // return false at the end of this block.
                // Note that this also prevents event bubbling,
                // which is probably what we want here, but won't 
                // always be the case.
                return false;
              }
            }

    </script>


    <a id="exportxt" href="#">SAVE PROJECT IN TXT FILE</a> 

<div id="editor"><p style="font-family:'Courier New', Courier, monospace; font-size:11px; color:#663300">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam luctus facilisis ante id luctus. Aliquam vestibulum, dui in pulvinar facilisis, felis nisl viverra nisl, nec ultrices neque tortor eget erat. Vivamus vel leo vehicula, condimentum quam aliquam, congue mauris. Pellentesque id lectus id nulla molestie vehicula sed at velit. Maecenas sit amet tristique nunc, in lobortis mi. Integer in turpis odio. Duis eget urna vestibulum, venenatis justo et, semper neque. Suspendisse in ante massa. Aenean massa nisl, tincidunt id nisl eu, convallis lobortis augue. Integer blandit augue eget nunc condimentum consectetur. Duis gravida nisl hendrerit, sagittis orci in, sollicitudin risus. Nullam elementum sem nec nunc facilisis, et semper metus tincidunt.

Phasellus ornare quis ipsum non scelerisque. In sollicitudin est placerat nibh porttitor pretium. Phasellus ac purus nulla. Phasellus in enim vel leo viverra sodales eget sit amet ante. Sed ultrices elementum nibh, tristique euismod nunc volutpat sit amet. Suspendisse potenti. Morbi feugiat diam tristique, euismod dui in, mattis diam. Vestibulum euismod commodo cursus. Proin posuere libero vitae purus blandit, in posuere erat malesuada. Donec ultrices vel velit in feugiat. Vestibulum suscipit erat urna, bibendum vestibulum dui varius sit amet.</p></div>

CREDITS, THIS ANSWER: How to use a link to call JavaScript?

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.