DOM Manipulation

Hi there. I’m experiencing an issue with my code for manipulating the DOM. I have a button and a paragraph in my HTML, and I want to toggle the visibility of the paragraph when the button is clicked. However, it doesn’t seem to be working.

I got inspired from the this source and wrote my code.
Here’s the link https://www.codecademy.com/courses/learn-intermediate-javascript/articles/implementing-modules-using-es-6-syntax

Here’s my simple HTML code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>DOM Manipulation </title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <script src="script.js"></script>
<button type="button" id="button"> This is my button</button>
  <p id="paragraph" style="display: none">This is hiden paragraph</p>
  <script src="./script.js"></script>
</body>

</html>

Here’s my JavaScript code:

const buttonElement = document.getElementById('button'); 
const paragraphElement = document.getElementById('paragraph');


const showParagraph = (domElement) => {
  if(domElement.style.display === 'none'){
    domElement.style.display = 'block';  
  } else {
    domElement.style.display = 'none'; 
  }
}

buttonElement.addEventListener('click', () => {
  showParagraph(paragraphElement); 
})

I’ve written a JavaScript function called showParagraph that takes a DOM element as an argument and toggles its display property between “none” and “block”. I’ve also attached an event listener to the button element, so when it’s clicked, it calls the showParagraph function with the paragraph element.

I am not exporting nor importing modules. I couldn’t experiment that far since my code doesn’t work. I wish somebody could tell me what’s wrong and how to fix this issue to make my code work. Appreciate! :+1:

Your code works fine in a sandbox. But you’re loading the script in the body before the rest of the HTML code (also you’re loading it twice). So the script is probably executed before the DOM is loaded. Try removing the first script and just keep the one right before the closing tag of the body and add the defer keyword:

<script src="./script.js" defer></script>

In addition: Is your script.js file located in the same folder as the index.html?

1 Like

It worked just fine!! Thanks :+1: That’s the thing of coding late at night. You aren’t focused enough.

1 Like