JavaScript Code


How to hide a paragraph using JavaScript?


Tutorials using JS

Hide a paragraph in JavaScript

In this tutorial, you shall learn how to hide a paragraph element in the document in JavaScript.

Solution

To hide a paragraph element in the document using JavaScript, we can use Element.style.display property. Get the paragraph element, and set its CSS display property with "none".

paragraphElement.style.display = "none";

Program

1. In the HTML, we have a Click me button and a paragraph with id myPara. When user clicks on the Click me button, we get the paragraph element by id myPara and set its CSS display property with none.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button>
<p id="myPara">This is a paragraph.</p>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
    //get the paragraph element
    const myPara = document.getElementById("myPara");
    //hide the paragraph element
    myPara.style.display = "none";
});
</script>

</body>
</html>

Copyright @2022