Home >Web Front-end >JS Tutorial >How Can I Hide and Show HTML Elements Using JavaScript's `display` Property?

How Can I Hide and Show HTML Elements Using JavaScript's `display` Property?

DDD
DDDOriginal
2024-12-14 05:35:13383browse

How Can I Hide and Show HTML Elements Using JavaScript's `display` Property?

Hide and Show Elements Using JavaScript

In web development, controlling the visibility of page elements is a common requirement. In this article, we explore how to hide and show elements in JavaScript using the display style property.

To hide an element, we set its display property to none. This removes the element from the page's visual flow, making it invisible to users. To show a hidden element, we simply set its display property back to a visible value, such as block or inline.

Example Scenario: Hiding and Showing Edit Functionality

Let's enhance a simple HTML structure with enhanced functionality:

<td>
  <a href="#" onclick="showStuff('answer1'); return false;">Edit</a>
  <span>

This code displays an "Edit" link and a hidden text area. Clicking the link should show the text area and hide the "Lorem ipsum" text.

Solution

We can modify the showStuff function to handle both hiding and showing elements:

function showStuff(id, text, btn) {
    document.getElementById(id).style.display = 'block';
    // hide the lorem ipsum text
    document.getElementById(text).style.display = 'none';
    // hide the link
    btn.style.display = 'none';
}

Here, we:

  • Show the target element (id) by setting its display property to block.
  • Hide the "Lorem ipsum" text (text) by setting its display property to none.
  • Hide the "Edit" link (btn) by setting its display property to none.

Modified Example

Incorporating these changes into the HTML:

<td>
  <a href="#" onclick="showStuff('answer1', 'text1', this); return false;">Edit</a>
  <span>

When the "Edit" link is clicked, it triggers the showStuff function, which shows the text area, hides the "Lorem ipsum" text, and hides the link itself.

The above is the detailed content of How Can I Hide and Show HTML Elements Using JavaScript's `display` Property?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn