Skip to main content

Exercise 2: Changing the Color and Text of an Element

Learn to dynamically modify the style and content of HTML elements using JavaScript. Discover how to easily and interactively change the color and text of an element.

Activity

  1. Create an HTML file with a button and an empty paragraph.

  2. When the button is clicked, change the paragraph's content and color using innerHTML and style.color.

Solution

Step 1: Create the index.html file

HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cambiar Color y Texto</title>
</head>
<body>
<h1>Ejercicio de Cambio de Color y Texto</h1>
<button id="colorButton">Cambia el color</button>
<p id="colorText"></p>

<script src="script.js"></script>
</body>
</html>

Step 2: Write the code in script.js

JavaScript
const colorButton = document.getElementById("colorButton");
const colorText = document.getElementById("colorText");

colorButton.addEventListener("click", () => {
colorText.innerHTML = "¡El color ha cambiado!";
colorText.style.color = "blue";
});
info

🔎Check the sectionJavaScript Basicswhere you will find more information on this topic.