JavaScript Basic - Display Data | Coding Learning Log#002

JavaScript is a powerful programming language that adds interactivity and dynamism to web pages. It allows people to create engaging user experiences, from simple animations and interactive forms to complex web applications. Sooo I'm starting learning JavaScript code and this is my learning log!

InnerHTML: Dynamically Changing HTML Content

JavaScript allows you to interact with and manipulate HTML content directly. One powerful way to do this is using the innerHTML property.

  • How it Works:
    • First, you give an HTML element a unique id attribute. For example: HTML<p id="myParagraph"></p>
    • Then, you can use JavaScript to access this element and modify its content: JavaScriptdocument.getElementById("myParagraph").innerHTML = "Hello, World!"; This code will replace the content within the <p> tag with the text "Hello, World!".

document.write(): For Testing, Not Production

document.write() is a convenient method for quickly displaying output on the page. For example:

document.write(1 + 1); 

This will display the number "2" directly on the page.

However, using document.write() in production environments can have unintended consequences:

  • Overwrites Existing Content: When document.write() is executed, it will overwrite all existing HTML content on the page. This can lead to unexpected and undesirable results.

Therefore, document.write() is primarily intended for testing purposes and should be avoided in production code.

console.log(): For Debugging

console.log() is a valuable tool for debugging JavaScript code. It allows you to display messages in the browser's console.

console.log("This message will appear in the console.");

This code will not be visible on the webpage itself, but it will be displayed in the browser's developer console, which can be accessed through the browser's developer tools.

window.alert(): Creating Pop-up Alerts

The window.alert() method displays a pop-up message box to the user.

window.alert("Hello, World!"); 

This will display an alert box with the message "Hello, World!".

You can also use alert() directly:

alert("Hello, World!"); 

Both methods produce the same result.

Example:

<button onclick="window.alert('Button Clicked!')">Click Me</button>

When this button is clicked, a pop-up message box will appear displaying the text "Button Clicked!".

Remember: While window.alert() can be useful for simple debugging or user notifications, overuse can be disruptive to the user experience.

Bucha Latte
Bucha Latte
Articles: 22

Leave a Reply

Your email address will not be published. Required fields are marked *