DEV Community

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

Collapse
 
fjones profile image
FJones • Edited

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>
</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, ...);
      return;
    }
  } 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.)