Categories
JavaScript Answers

How to print specific part of webpage with JavaScript?

Spread the love

Sometimes, we want to print specific part of webpage with JavaScript.

In this article, we’ll look at how to print specific part of webpage with JavaScript.

How to print specific part of webpage with JavaScript?

To print specific part of webpage with JavaScript, we can open a new window and print its contents.

For instance, we write

const printInfo = (ele) => {
  const openWindow = window.open("", "title", "attributes");
  openWindow.document.write(ele.previousSibling.innerHTML);
  openWindow.document.close();
  openWindow.focus();
  openWindow.print();
  openWindow.close();
};

to define the printInfo function that takes the ele element.

In it, we call window.open to open the window.

And then we call openWindow.document.write to write the ele‘s content with ele.previousSibling.innerHTML.

We call openWindow.focus to focus on the window.

Next, we call openWindow.print to print the window.

And then we call close to close the window.

Conclusion

To print specific part of webpage with JavaScript, we can open a new window and print its contents.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *