Hey there, future web developers! Did you know JavaScript has several ways to display data? Whether you're updating a web page or testing code, JavaScript's got you covered!
Let's break it down into four simple methods: Quick and easy, just like we like it. First up: using innerHTML() This is like filling in a shape or form. JavaScript finds an existing element by its ID and updates the content.
Here's how it works: This code grabs the <p> tag with the id="demo" and changes its content to. . .
you guessed it Hello World! Super handy for updating content dynamically. Next, we have document.
write() It’s like the loudspeaker of JavaScript. It outputs directly into the HTML document But watch out! If you use document.
write() after the page has loaded, it wipes out everything on your page. See this example: Here we run the code when the user clicks the button. So.
. . after the page has finished loading.
Oops! It replaces our entire page. So great for quick testing.
But not for production. Want to grab someone's attention? Use an alert box with window.
alert() Or just alert() since the window part is optional! This pops up a box with the result. Great for quick notifications, but don’t overuse it .
. . unless you like annoying your users.
And finally, the secret weapon for debugging: console. log() Think of it like a journal for your code. It logs messages straight to the browser console.
Use this to test your code behind the scenes without interrupting the user experience. It's a developer's best friend! When testing console methods, you need to have the console view visible.
This is usually opened by pressing F12. One last trick: while JavaScript doesn’t have a direct send to printer function, you can use window. print() to print the current page.
Easy peasy! Just one button click, and voilà: Old timey paper printed content. So there you have it!
Four ways to display data in JavaScript, plus a bonus printing tip. Try them out, and see which one works best for your projects! Thanks for watching!
Like and subscribe to get notified about our latest videos! For more coding tips and tricks, keep it locked right here on W3Schools. com!
Don't forget to try out what you've learned in our interactive editor. Happy coding!