innerHTML, and more.
let name = "John Doe"; console.log("Hello, " + name);
This will output the string
"Hello, John Doe" in the browser's developer console.
document.write after the page has finished loading will overwrite the entire page.
Here is an example of how to use
document.write to create a simple unordered list:
document.write("<ul>"); document.write("<li>Apples</li>"); document.write("<li>Oranges</li>"); document.write("<li>Bananas</li>"); document.write("</ul>");
This will create an unordered list on the web page with the list items "Apples", "Oranges" and "Bananas".
innerHTML can be used to display data on the web page. This property can change the content of an HTML element, and it can also be used to create new HTML elements. Here is an example of how to use
innerHTML to add a new list item to an existing unordered list:
<ul id="fruits"> <li>Apples</li> <li>Oranges</li> </ul>
let newFruit = "Bananas"; document.getElementById("fruits").innerHTML += "<li>" + newFruit + "</li>";
This will add a new list item "Bananas" to the unordered list with the id "fruits".
The window.alert() method creates a dialog box with a message and an OK button. The user must click OK to close the dialog box. Here is an example of how to use
window. alert to display a message to the user:
let message = "Hello, World!"; window.alert(message);
We should also mention that
alert('Hello!') or by referencing the global object specifically:
window.alert('Hello!'). They're the same and you can use whichever you prefer, but it's considered more explicit to use the fully qualified method name
window.alert() as it's less prone to naming conflicts.
console.table() may not be supported in older browsers.
window.print() method, which can be used to print the content of the current browser window.
Best Practices for Beginners
innerHTMLto change the content of existing HTML elements, and use
document.writeonly if you are creating a new web page.
Be careful when using
document.writeafter the page has finished loading, as it will overwrite the entire page.
Always test your code in multiple browsers to ensure that it works correctly.
Learn to use browser dev tools so you can test and debug your code.
Avoid using global variables or overwriting them.
console.log()method is a widely used and easy-to-use method for debugging and displaying data in the browser's developer console.
document.write()and innerHTML methods are used to display data on the web page itself, but they have different use cases and should be used accordingly.
window.alert()method is used to display a dialog box with a message and an OK button, it's mostly used for debugging or testing purposes.
console.group()methods are advanced techniques for debugging, that can make it easier to understand the data structure.
window.print()method, which can be used to print the content of the current browser window.