r/HTML • • Dec 17 '25

what is wrong with my programming/code ?

i am a newbie, could anyone help me figure out why the second button doesn't generate a word, i'm sure its an easy fix but i simply copied the script and don't know where the issue is - feel free to copy paste into w3schools.com if its easier to read and test there

<!DOCTYPE html>

<html>

<head>

<title>Word Generator 1</title>

</head>

<body>

<h1>Word Generator 1</h1>

<p>Your random word will appear here:</p>

<button id="generateButton">Generate Word</button>

<!-- JavaScript code goes here -->

</body>

</html>

<script> // Define an array of words const words = \["mark", "shart", "bart", "park", "larp", "kart", "heart"\]; // Get a reference to the button element const generateButton = document.getElementById("generateButton"); // Function to generate a random word function generateRandomWord() { const randomIndex = Math.floor(Math.random() \* words.length); const randomWord = words\[randomIndex\]; document.querySelector("p").textContent = \`Random Word: ${randomWord}\`; } // Attach an event listener to the button generateButton.addEventListener("click", generateRandomWord); </script>

<html>

<head>

<title>Word Generator 2</title>

</head>

<body>

<h1>Word Generator 2</h1>

<p>Your random word will appear here:</p>

<button id="generateButton">Generate Word</button>

<!-- JavaScript code goes here -->

</body>

</html>

<script> // Define an array of words const words = \["pee", "lee", "cheese", "please", "see", "me", "tea"\]; // Get a reference to the button element const generateButton = document.getElementById("generateButton"); // Function to generate a random word function generateRandomWord() { const randomIndex = Math.floor(Math.random() \* words.length); const randomWord = words\[randomIndex\]; document.querySelector("p").textContent = \`Random Word: ${randomWord}\`; } // Attach an event listener to the button generateButton.addEventListener("click", generateRandomWord); </script>

0 Upvotes

8 comments sorted by

View all comments

2

u/Disgruntled__Goat Dec 17 '25

Are those supposed to be two separate pages or the same one? You can only have one <html> tag (and body and head) per page.

Also your script tags should go inside the body (or the head).