Exercise 1: alert, console.log, and innerHTML in JavaScript
Master the essential fundamentals of JavaScript by learning how to use alert, console.log, and innerHTML. This tutorial is ideal for beginners who want to understand how to display messages and manipulate content on a web page.
The main goal is to become familiar with three of the basic output methods in JavaScript:alert,console.log, andinnerHTMLYou will learn how to display pop-up messages, console messages, and how to change the content of a web page.
Activity
-
Create a basic HTML file called index.html and add the main HTML structure.
-
In the HTML file, add a button and an empty text element where we will display a message.
-
Create a JavaScript file called script.js and write the code so that, when the button is clicked, the program performs three actions:
-
Display a pop-up message using alert.
-
Print a message to the console using console.log.
-
Change the text of the element in the HTML using innerHTML.
Solution
Step 1: Create the index.html file
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ejercicio Básico con JavaScript</title>
</head>
<body>
<h1>Ejercicio de Alert, Console y innerHTML</h1>
<!-- Botón para activar el ejercicio -->
<button id="miBoton">Haz clic aquí</button>
<!-- Contenedor para mostrar el mensaje con innerHTML -->
<p id="miMensaje"></p>
<!-- Vincular el archivo JavaScript -->
<script src="script.js"></script>
</body>
</html>
Step 2: Write the code in script.js
// Seleccionar el botón y el elemento donde pondremos el mensaje
const boton = document.getElementById("miBoton");
const mensaje = document.getElementById("miMensaje");
// Agregar un evento 'click' al botón para ejecutar las acciones
boton.addEventListener("click", () => {
// 1. Mostrar un mensaje emergente usando alert
alert("¡Hola! Este es un mensaje de alerta.");
// 2. Mostrar un mensaje en la consola usando console.log
console.log("Este es un mensaje en la consola.");
// 3. Cambiar el contenido de HTML usando innerHTML
mensaje.innerHTML = "Este es un mensaje que aparece en la página.";
});
🔎Check the sectionJavaScript Basicswhere you will find more information on this topic.