Skip to content
the poor coder

toggle hidden attribute javascript

Poor Man
Published
Reading time
1 min read
On this page

How to Toggle Hidden Attribute in JavaScript#

If you want to hide or show elements on your web page dynamically, you can use the hidden attribute in HTML, which is a boolean attribute that can be added to any element. When the hidden attribute is present, the element is hidden; otherwise, it is visible.

However, if you want to toggle the hidden attribute using JavaScript, you can use the following methods:

Method 1: Using Plain JavaScript#

You can use plain JavaScript to toggle the hidden attribute of an element by accessing its style object and setting its display property to either "none" (to hide) or "block" (to show). Here's an example:

Text

var element = document.getElementById("my-element");

if (element.getAttribute("hidden") !== null) {
  element.removeAttribute("hidden");
  element.style.display = "block";
} else {
  element.setAttribute("hidden", "");
  element.style.display = "none";
}

In this code, we first check if the element has the hidden attribute. If it does, we remove it and set its display property to "block" to show it. If it doesn't, we add the hidden attribute and set its display property to "none" to hide it.

Method 2: Using jQuery#

If you're using jQuery, you can toggle the hidden attribute of an element using its toggle() function. Here's an example:

Text

$("#my-element").toggle();

This code will toggle the hidden attribute of the element with ID "my-element". If it's hidden, it will be shown; if it's shown, it will be hidden.

These are some of the ways you can toggle the hidden attribute in JavaScript. Choose the one that works best for your use case and enjoy the flexibility and power of dynamic web pages.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC