There are several ways to produce outputs in JavaScript:
Changing the contents of an HTML element
- JavaScript can be used to modify the content of HTML elements by accessing them through the Document Object Model (DOM). E.g.:
chosenElement = document.getElementById("example");
chosenElement.innerHTML = "Hello World";- The first line of code uses the
document.getElementById()method to retrieve the HTML element with the ID ”examplefrom the document’s DOM (Document Object Model) - The returned element is assigned to the variable
chosenElement, which allows further manipulation of that element - The second line of code modifies the content within the
chosenElementHTML element - The
innerHTMLproperty allows direct access to the HTML content within an element - In this case, the content of
chosenElementis changed to “Hello World”, effectively replacing any existing content with this new text
Writing directly to the document
- JavaScript can write directly to the document using the
document.write()method. E.g.
document.write("Hello World");- This code writes the text “Hello World” directly to the webpage.
- This usage of this is strongly discouraged in real life, APIs like this are known as injection sinks, and are potentially a vector for cross-site scripting (XSS) attacks, if the input originally came from an attacker.
Using an alert box
- JavaScript provides the
alert()function to display a pop-up alert box with a message. E.g.
alert("Hello World");- This code triggers an alert box with the message “Hello World”
Alert Box with the words ‘Hello World’