Printing to the Console with console.log()
Any type of data can be logged to the console, including strings, numbers, arrays, and objects, and either the contents of, or a text representation of, the value will be displayed.
console.log() is frequently used for debugging – developers use it to view the contents of variables or the result of a function to make sure their code is working in an unobtrusive place.
The syntax for the console.log() method is as follows:
- MESSAGE is the text or object your wish to see displayed in the console
You may also be looking to print data to the webpage being viewed. This is done using the document.append() method.
The syntax for appending elements to the end of the current page/document is as follows:
- CONTENT should be one or more HTML elements to be appended to the end of the current page
- body is the document element you wish to append to – in this case, the body of the HTML document is specified
- You could also append to the head or other root HTML element, but if you want the content to be visible, it should be appended to the body element
- If you wish to prepend (add data to the beginning of) the document, document.prepend(CONTENT) can be used in the same way
I’ll provide a quick example of this one, as you will also need to construct a HTML object containing the data you wish to print/append/prepend:
var paragraphElement = document.createElement("p"); var myText = document.createTextNode("Linux is great!"); paragraphElement.appendChild(myText); document.body.append(paragraphElement);
The comments should explain what’s going on above. The result of running the above will be to add the text “Linux is great!” to the end of the current web page.
Note that these changes aren’t permanent! Refreshing the page will return it to it’s original state.
Printing to a Printer with window.print()