How js elegantly prints the contents of a div tag

now there is a printing function that requires printing the contents of specific div blocks. I have implemented a simple version

printElement = (elementId) => {
  let printElement = document.getElementById(elementId)
  let newContent = printElement.innerHTML
  let oldContent = document.body.innerHTML
  document.body.innerHTML = newContent
  window.print()
  window.location.reload()
  document.body.innerHTML = oldContent
}

you can print in this way, but if you click confirm or cancel the result, the page will be reloaded again. Is there a better way to print?

Feb.16,2022
Isn't the line

window.location.reload () an overloaded page?


window.open () opens a small new window and prints

in the new window.
Menu