I am trying to perform an exercise where I toggle the visibility of an element by accessing its ID. I can get it to disappear when I click it. However I dont understand what is wrong with my code so that it doesn’t reappear when clicked. thanks
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#button {
display: block;
}
</style>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="p1Text">Hello world</p>
<button id="button">Buttonni</button>
<script>
let button = document.getElementById("button");
document.getElementById("button").onclick = function() {
if (button.style.display === "none") {
button.style.display = "block";
} else {
button.style.display = "none";
}
};
</script>
</body>
</html>
2
Answers
You are making the button disappear once it is clicked. Is that what you are meaning to make disappear?
Or are you trying to make the following paragraph disappear on the button click?
If that is what you want to make disappear, you have to change the getElementByID to the correct ID.
Currently, you are doing:
which is getting the ID of the button, instead, get the element of the paragraph
that should fix it
The issue with your code lies in the condition you’re checking for toggling the visibility of the button. Currently, you’re checking the
style.display
property of the button element itself, but it’s initially set to "block" in your CSS. To fix this, you should check thestyle.display
property of the paragraph element (p1Text
) instead. Here’s the updated code:Now, when you click the button, it should toggle the visibility of the paragraph (
p1Text
) between "block" and "none".