DEV Community 👩‍💻👨‍💻

Discussion on: How to make a "Save" button using JavaScript?

prakhart111 profile image
Prakhar Tandon

This can be done through Blob constructor.
Read More below.


t3cstudios profile image
T3C Studios Author

Great! Works fine as far as the saving goes..

Just how can I select the div class I want the button to save? I cannot figure that part out..

I have this on the button:
onclick="download('Test', 'MyTasks.txt', 'text/plain')"

And the 'Test' is the text which will appear in the text file, but how can I make it be instead of "Test" whatever is in my certain div class?

fjones profile image
FJones • Edited on

You're likely looking for a solution that gets a div containing or adjacent to your button, or a child of an adjacent element. I'd suggest something along these lines:

<div class="has-exportable-content">
  <button type="button" onclick="saveHandler">save</button>
  <div class="exportable-content">text</div>
Enter fullscreen mode Exit fullscreen mode

With the JS along these lines:

function saveHandler({ currentTarget }) {
  let elem = currentTarget;
  do {
    elem = elem.parentElement;

    if (elem && elem.classList.contains("has-exportable-content")) {
      const { textContent } = elem.querySelector(".exportable-content") || {};
      download(textContent, ...);
  } while (elem && elem !== elem.getParentNode());
Enter fullscreen mode Exit fullscreen mode

(Some alternatives notwithstanding depending on your particular use-case. e.g. innerText vs textContent or parentNode vs parentElement, and target vs currentTarget.)

valeriavg profile image

You can get contents with

Enter fullscreen mode Exit fullscreen mode