Show Content with JavaScript Summary

JavaScript can reveal content that was hidden when a page first loaded. This is useful for answers, instructions, menus, messages, and other information that should appear only when it is needed.

Showing hidden content requires two parts. CSS hides the HTML element at first, and JavaScript changes its display value when the content should appear.

How to Show Hidden Content

First, the HTML needs an element for JavaScript to find. This paragraph has an ID attribute named answer.

<p id="answer">The answer is blue.</p>

The CSS hides the paragraph when the page loads:

#answer {
	display: none;
}

JavaScript can reveal it with one line:

document.querySelector('#answer').style.display = 'block';

When this code runs, the paragraph changes from display: none to display: block, so it becomes visible.

Find the Hidden Element

The first part finds the element that JavaScript will show:

document.querySelector('#answer')

querySelector() finds an HTML element using a CSS selector. The #answer selector finds the element with id="answer".

Change the Display Style

The second part changes the element’s inline CSS:

.style.display = 'block';

style.display represents the element’s display property. Giving it the value block makes the hidden paragraph appear and take up its normal space on the page.

To hide the paragraph again, JavaScript can set the same property to none:

document.querySelector('#answer').style.display = 'none';

When Websites Show Content

Websites often hide information until someone asks to see it. This keeps a page simple while still making more content available.

  • Reveal an answer to a question.
  • Open a navigation menu.
  • Display more details about a product.
  • Show a message after an action.

The example on this page runs immediately. In a complete website, the same line could run after someone clicks a button.

Try Showing the Answer

In the sandbox, select Update Code to reveal the hidden answer. Then change the words inside the paragraph and update the code again.

To test the opposite result, change 'block' to 'none'. The paragraph will remain hidden because both the CSS and JavaScript will use the hidden display value.

Interactive Demo

The hidden content is now visible.

Code Sandbox

AI Tutor