
JavaScript
JavaScript Output
JavaScript Display Possibilities
It is one of the fundamental programming languages, enabling developers to display data in various formats. For example
- Use innerHTML or innerText to add content to an HTML element.
- Inserting data directly into the output of an HTML document with document.write ().
- Use the window.alert() method to display data in a pop-up alert box.
- Writing logging information into the browser console with console.log ().
Using inner HTML
It is the most commonly used method to change and display the content of an HTML element. An HTML element can be easily accessed using the document.getElementById(id) method. Change the content of an HTML element by following the steps mentioned below:
- Select and access an HTML element using the id attribute.
After selecting, change the HTML element’s content using the innerHTML property.
Using innerText
Accessing the HTML element is the same in all formats, i.e., the document.getElementById(id) method. Select and access the HTML element whose inner text you want to change. Use the innerText property, and the displayed text will be changed.
innerHTML and innerText are confusing to some. Keep in mind, innerHTML is used to change the entire HTML element. Whereas, the innerText method only changes the text of an HTML element.
Using document.write()
If you are only testing the display, use the document.write() method.
Important Note: Keep in mind that all existing HTML data will be deleted once the document.write() method is used, and the HTML document is loaded or saved. Therefore, use it only for testing purposes.
Using a window.alert()
This format is used to add and display text or a note in the pop-up or alert box.
When using this method to display data, it is not necessary to write the window keyword. It is because the window is the main object in JavaScript. So, any variable you create in JavaScript, the window will be a part of it. It is a default function, which is why specifying the window keyword is optional.
Using console.log()
To display all HTML data for debugging, use the console.log () method in the browser.
JavaScript Print
JavaScript has no print function. That’s why it can not be used to access any of the output devices. However, the window.print() method can be used in the browser to print any JavaScript content on the window you are currently working in.