When you want to print your browser’s current webpage, you can use the
window.print() method. The
window.print() method will print the contents of the currently active tab in your browser.
- Modifying the
innerHTMLproperty of an HTML element to dynamically update the content on the page.
- Using the
console.log()method to print messages to the browser console.
- Writing output directly to the HTML document using the
- Using the
Window.alert()method to display messages in an alert box.
Print using innerHTML method
Here’s an example of how to change the
innerHTML property of an element to print a message:
<html> <head> <title>Changing innerHTML property</title> </head> <body> <div id="my-element">Original content</div> <script> // Select the element var myElement = document.getElementById("my-element"); // Change the innerHTML property myElement.innerHTML = "New content!"; </script> </body> </html>
In this example, we start with a
div element that has an
id of “my-element” and some initial content (“Original content”). Then, in the
script tag, we use the
getElementById method to select that element and store it in a variable called
myElement. Finally, we change the
innerHTML property of
myElement to “New content!”. When the script runs, the content of the
div element will be updated to “New content!”.
Print with console.log() method
let name = "Mir"; console.log(name); // prints: Mir
Print with document.write() method
Here is an example of using document.write() to write a message to a document:
In this example, the string “Hello, world!” will be written to the document.
You can also use
document.write() to write HTML code to the document, like this:
document.write("<h1>Welcome to my website</h1>");
In this example, the HTML code for a heading element will be written to the document.
Note that using
document.write() can be a bit tricky, as it can overwrite the entire document if not used carefully. In general, it’s better to use other methods, such as
innerHTML, to manipulate the document content.
Print using window.alert() method
window.alert() method that displays an alert box with a message to the user. When you call window.alert() with a message as an argument, a dialog box will appear in the user’s browser window, displaying the message you specified.
Here’s an example of using
window.alert() to display a message to the user: