Tips on adjusting my script to focus on particular text within a div in HTML

I'm currently learning how to code and working on a text generator that allows users to edit text and export it as .DOCX. I came across this script called jsfiddl on the website npmjs, which enables exporting HTML to .DOCX. However, I'm having trouble figuring out how to make the script export HTML text from a specific div, like in my example where I want to export content in <div id="exportContent">.

Note: When I tried organizing the script in jsfiddle with both HTML and JavaScript, it didn't work.

<!DOCTYPE html>
<html>

<head>
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb9f949883bbcfd5cbd5cb">[email protected]</a>/build/index.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
</head>

<body>

    <h1>DOCX browser Word document generation</h1>

    <button type="button" onclick="generate()">Click to generate document</button>

    <script>
        function generate() {
            const doc = new Document();

            const paragraph = new Paragraph("Hello World");
            const institutionText = new TextRun("Foo Bar").bold();
            const dateText = new TextRun("Github is the best").tab().bold();
            paragraph.addRun(institutionText);
            paragraph.addRun(dateText);

            doc.addParagraph(paragraph);

            const packer = new Packer();

            packer.toBlob(doc).then(blob => {
                console.log(blob);
                saveAs(blob, "example.docx");
                console.log("Document created successfully");
            });
        }
    </script>

<div id="exportContent">
   Lorem Ipsum is simply dummy text of the printing and typesetting industry.
   Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
   <span  class="a" contenteditable="true" >
  -----------------YOUR TEXT HERE--------------------
    </span> took a galley of type and scrambled it to make a type specimen book. 
   It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. 
   It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
   and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

</body>

</html>

Answer №1

To export the HTML content within #exportContent, simply extract the innerHTML of #exportContent and pass it to your document.

function generate() {
    const doc = new Document();
    
    // here's the content you want to export
    let exportThis = document.getElementById("exportContent").innerHTML
    
    const paragraph = new Paragraph(exportThis);

    doc.addParagraph(paragraph);

    const packer = new Packer();

    packer.toBlob(doc).then(blob => {
        console.log(blob);
        saveAs(blob, "example.docx");
        console.log("Document created successfully");
    });
}
<!DOCTYPE html>
<html>

<head>
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4d0dbd7ccf4809a849a84">[email protected]</a>/build/index.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
</head>

<body>

    <h1>Generate Word Document in Browser with DOCX</h1>

    <button type="button" onclick="generate()">Click to Generate Document</button>


  <div id="exportContent">
     Lorem Ipsum is simply dummy text of the printing and typesetting industry.
     Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
     <span  class="a" contenteditable="true" >
    -----------------YOUR TEXT HERE--------------------
      </span> took a galley of type and scrambled it to make a type specimen book. 
     It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. 
     It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
     and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </div>

</body>

</html>

If you aim for users to edit the text, consider using a different element than a <div>.

function generate() {
    const doc = new Document();
    
    // this is what you want to export
    let exportThis = document.getElementById("exportContent").value
    
    const paragraph = new Paragraph(exportThis);

    doc.addParagraph(paragraph);

    const packer = new Packer();

    packer.toBlob(doc).then(blob => {
        console.log(blob);
        saveAs(blob, "example.docx");
        console.log("Document created successfully");
    });
}
textarea {
  margin-top:2em;
  width:100%;
}
<!DOCTYPE html>
<html>

<head>
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f1959e9289b1c5dfc1dfc1">[email protected]</a>/build/index.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
</head>

<body>

    <h1>Generate Word Document in Browser with DOCX</h1>

    <button type="button" onclick="generate()">Click to Generate Document</button>


<textarea id="exportContent">
  -----------------Type your content here to be exported--------------------


</textarea>

</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Leaflet to make geojson XMLHttpRequests

Recently, I've been exploring the world of JavaScript and attempting to map around 2,200 data points in Leaflet. Despite following a helpful tutorial on pulling data from a geojson file and displaying it on a map, I can't seem to make it work wit ...

Executing JavaScript files stored on my server using the Node.js command line interface

I need guidance on configuring an app that relies on running node generate.js and node generate_texts_index.js in the command prompt. These files are essential for building the necessary data for the app to function correctly. Running these files locally a ...

What could be causing the issue of *ngIf not displaying content within ng-container in Angular

I am struggling to close a bootstrap alert box by clicking on the close button using *ngIf. When I click on (close), I set isError to false. Even though I can see isError being logged as false, the ng-container is not disappearing. Here is my code: <d ...

The gaps separating rows

I'm struggling with getting my divs to look like a table, especially when it comes to highlighting a selected row. I've tried adjusting padding and margins without success. Does anyone have any suggestions on how I can achieve this effect? .ta ...

sass-loader Unable to locate @import url

Currently, I am working on a project using nuxt.js in conjunction with fastify.js (fastify-vue-plugin), and I am in the process of configuring my styling. Although the scss compiles smoothly and functions correctly, I am facing an issue during the build p ...

Set the div to have a position of absolute, disregarding any other parent divs that may also have position absolute set

Is there a way to bring an outsider class <div> to the front of all others, even when all <div> elements are set as position: absolute;? How can the .free-object, which is inside .left, overlap both .left and .right? I have tried using z-ind ...

Is it possible to link multiple references to a single Element/Node?

I am working on a function component that needs to pass the incoming ref from the parent to a div it is rendering. Additionally, I want to create and assign a separate ref inside the component to the same div. However, due to an element only accepting one ...

After using promise.all, I successfully obtained an array of links. Now, how do I calculate the total number of links in the array?

function verifyAndTallyURLs(linksArray) { let validations = linksArray.map((link) =>{ return fetch(link) .then((response) => { return { webpageURL: response.url, status: response.status, ...

How to effectively utilize multiple Vue instances in your project?

My inquiry is somewhat linked to a similar question on Stack Overflow, but I am uncertain about the level of discouragement towards the approach discussed in relation to Vue. In my situation, I am working on a project where the DOM is generated entirely b ...

Deciphering key-value pairs that are separated by commas

I am looking to convert the following format: realm="https://api.digitalocean.com/v2/registry/auth",service="registry.digitalocean.com",scope="registry:catalog:*" Into this JSON object: { realm: "https://api.digitaloce ...

Transmitting data as an array using JQuery

$('[data-toggle="mftapproveCheck"]').click(function () { var selected = $("#checkboxes input:checked").map(function (i, el) { return el.value; }).get(); //alert("selected = [" + selected + "]\nas int = \"" + selected.join(";") ...

jQuery modal fails to display

I am currently experiencing an issue with my jQuery dialog that is not displaying after clicking a radio button. Previously, the dialog was showing properly, but after implementing some script for submitting from the dialog, it stopped showing up when th ...

Error: The npm-link library encountered an invalid hook call

Problem Description: I am working on developing a package named eformless. To set up the package, I utilized CRA to create a directory named sandbox where I linked the package. However, I keep encountering an error when attempting to launch the sand ...

CSS guidelines for handling single line breaks with the white-space property set to pre-wrap

Is it considered acceptable to include solitary carriage return characters in an HTML block styled with white-space: pre-wrap? I am working with an application that receives SOAP messages and logs them to a file. The logging process involves removing new- ...

Having trouble with the functionality of Bootstrap 5 carousel?

I've been attempting to integrate this carousel into my Bootstrap 5 webpage. I found it on Codepen - https://codepen.io/sahil-verma/pen/wxXryx Thus far, I've copied the code into my webpage and linked the corresponding CSS within style tags, sim ...

Error message in console: React Form showing "Form submission canceled due to lack of connection" despite successful submission

I am facing an issue with my form in my React app. Even though the form is successfully submitting data to a list of boxes, I received an error in the console. The error message says: Form submission canceled because the form is not connected In my Rea ...

Executing javascript code within the success function of the $ajax method in jQuery: A step-by-step guide

The code snippet below includes a comment before the actual code that is not running as expected. $(document).on('click', '#disable_url', function (e) { e.preventDefault(); var items = new Array(); $("input:checked:no ...

The functionality of document.elementFromPoint(x, y) seems to be faulty in accurately identifying child elements

I've been trying to retrieve the element over which a "drop" event occurs, but I keep getting unexpected results. It consistently returns parent elements instead of the actual child element where the dragged element is dropped on. For a full code exa ...

The array is devoid of any elements, despite having been efficiently mapped

I'm facing some challenges with the _.map function from underscore.js library (http://underscorejs.org). getCalories: function() { var encode = "1%20"; var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#"; _.m ...

Individuals have the capability to utilize .php as an image extension

It seems that someone is able to use any type of extension as long as they add .png at the end of the link. is currently being used, causing users on my website to log out when visiting the homepage. I tried to stop this issue, but unfortunately, my sol ...