Outputs in JavaScript (OCR A Level Computer Science)
Revision Note
Written by: Becci Peters
Reviewed by: James Woodhouse
Outputs in Javascript
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 "example
" from the document's DOM (Document Object Model)The returned element is assigned to the variable
chosenElement
, which allows further manipulation of that elementThe second line of code modifies the content within the
chosenElement
HTML elementThe
innerHTML
property allows direct access to the HTML content within an elementIn this case, the content of
chosenElement
is 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
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'
Last updated:
You've read 0 of your 5 free revision notes this week
Sign up now. It’s free!
Did this page help you?