- JavaScript — How to show and hide div by a button click
- Learn JavaScript for Beginners 🔥
- About
- Search
- Tags
- How to Hide Div in JavaScript?
- Conclusion
- Related Tutorials
- Popular Courses by TutorialKart
- Salesforce
- SAP
- Accounts
- Database
- Programming
- App Developement
- Mac/iOS
- Apache
- Web Development
- Online Tools
- How to hide HTML element with JavaScript?
- Using the hidden property
- Syntax
- Example
- Using the style.display property
- Syntax
- Example
- Using the style.visibility property
- Syntax
- Example
- Показать и скрыть элемент на JS
- HTML структура
- CSS код
- JavaScript код
- Демонстрация показа и скрытия элемента
JavaScript — How to show and hide div by a button click
To display or hide a by a click, you can add the onclick event listener to the element.
The onclick listener for the button will have a function that will change the display attribute of the from the default value (which is block ) to none .
For example, suppose you have an HTML element as follows:
The element above is created to hide or show the element on click.
You need to add the onclick event listener to the element like this:
When you click the element again, the display attribute will be set back to block , so the will be rendered back in the HTML page.
Since this solution is using JavaScript API native to the browser, you don’t need to install any JavaScript libraries like jQuery.
You can add the JavaScript code to your HTML tag using the tag as follows:
Feel free to use and modify the code above in your project.
I hope this tutorial has been useful for you. 👍
Learn JavaScript for Beginners 🔥
Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.
A practical and fun way to learn JavaScript and build an application using Node.js.
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
How to Hide Div in JavaScript?
To hide a div using JavaScript, get reference to the div element, and assign value of "none" to the element.style.display property.
Conclusion
In this JavaScript Tutorial, we learned how to hide a div using JavaScript.
Related Tutorials
- How to Change Border Color of Div in JavaScript?
- How to Change Border Radius of Div in JavaScript?
- How to Change Border Style of Div in JavaScript?
- How to Change Border Width of Div in JavaScript?
- How to Change Bottom Border of Div in JavaScript?
- How to Change Font Color of Div in JavaScript?
- How to Change Font Family of Div in JavaScript?
- How to Change Font Size of Div in JavaScript?
- How to Change Font Weight of Div in JavaScript?
- How to Change Height of Div in JavaScript?
- How to Change Left Border of Div in JavaScript?
- How to Change Margin of Div in JavaScript?
- How to Change Opacity of Div in JavaScript?
- How to Change Padding of Div in JavaScript?
- How to Change Right Border of Div in JavaScript?
- How to Change Text in Div to Bold in JavaScript?
- How to Change Text in Div to Italic in JavaScript?
- How to Change Top Border of Div in JavaScript?
- How to Change Width of Div in JavaScript?
- How to Change the Background Color of Div in JavaScript?
- How to Change the Border of Div in JavaScript?
- How to Clear Inline Style of Div in JavaScript?
- How to Insert Element in Document after Specific Div Element using JavaScript?
- How to Underline Text in Div in JavaScript?
- How to get Attributes of Div Element in JavaScript?
Popular Courses by TutorialKart
Salesforce
SAP
Accounts
Database
Programming
App Developement
Mac/iOS
Apache
Web Development
Online Tools
©Copyright - TutorialKart 2023
How to hide HTML element with JavaScript?
In this tutorial, we will learn how to hide HTML element with JavaScript.
Hiding an HTML element can be performed in different ways in JavaScript. In this tutorial, we will see the three most popular ways of doing it −
- Using the hidden property
- Using the style.display property
- Using the style.visibility property
Generally, we use the hidden attribute to hide a particular element. We can toggle between hiding and showing the element by setting the hidden attribute value to true or false, respectively.
In the other two ways, we use the style object of the element. We have two properties in the style object to hide the HTML element, one is the display, and another one is the visibility.
In JavaScript, we can use both of these properties to hide the HTML elements, but the main difference between these two is when we use style.visibility property, then the specific tag is not visible, but the space of the tag is still allocated. Whereas in style.display property, not only is the tag hidden but also there is no space allocated to that element.
Using the hidden property
In JavaScript, the hidden property of an element is used to hide an element. We set the hidden properties value to true to hide the element.
Syntax
Following is the syntax to use hidden property −
document.getElementById('element').hidden = true
In the above syntax, ‘element’ is the id of an HTML element, and by using document.getElementById method, we are accessing the element and changing its hidden property to true to hide the element.
Example
In the below example, we have used the hidden property to hide a div element using JavaScript.
html> body> div id="dip"> Click the below buttons to hide or show this text. /div>br> button onclick="hide()"> Hide Element /button> button onclick="show()"> Show Element /button> script> function hide() document.getElementById('dip').hidden = true > function show() document.getElementById('dip').hidden = false > /script> /body> /html>
Using the style.display property
In JavaScript, style.display property is also used to hide the HTML element. It can have values like ‘block,’ ‘inline,’ ‘inline-block,’ etc., but the value used to hide an element is ‘none.’ Using JavaScript, we set the style.display property value to ‘none’ to hide html element.
Syntax
Following is the syntax to hide HTML elements using style.display property in JavaScript.
document.getElementById('element').style.display = 'none'
In the above syntax, ‘element’ is the id of an HTML element, and by using document.getElementById method, we are accessing the element and changing its style.display property to ‘none’ to hide the element.
Example
In the below example, we have used the style.display property to hide a div element using JavaScript.
html> style> #myDIV width: 630px; height: 300px; background-color: #F3F3F3; > /style> body> p> Click the "Hide Element" button to hide the div element. /p> button onclick="hide()"> Hide Element /button> div id="myDIV"> Hello World! This is DIV element /div> script> function hide() document.getElementById('myDIV').style.display = 'none' > /script> /body> /html>
Using the style.visibility property
In JavaScript, style.visibility property is also used to hide the HTML element. It can have values like ‘visible,’ ‘collapse,’ ‘hidden’, ‘initial’ etc., but the value used to hide an element is ‘hidden’. Using JavaScript, we set the style.visibility property value to ‘hidden’ to hide html element.
Syntax
Following is the syntax to hide HTML elements using style.visibility property in JavaScript −
document.getElementById('element').style.visibility = 'hidden'
In the above syntax, ‘element’ is the id of an HTML element, and by using document.getElementById method, we are accessing the element and changing its style.visibility property to ‘hidden’ to hide the element.
Example
In the below example, we have used the style.visibility property to hide element using JavaScript.
html> style> #dip width: 630px; height: 300px; background-color: #F3F3F3; > /style> body> p> Click the "Hide Element" button to hide the div element. /p> button onclick="hide()"> Hide Element /button> button onclick="show()"> Show Element /button> div id="dip"> Hello World! This is DIV element /div> script> function hide() document.getElementById('dip').style.visibility = 'hidden'; > function show() document.getElementById('dip').style.visibility = 'visible'; > /script> /body> /html>
In the above output, users can see the element is hidden using style.visibility property, but the element still occupies its space in the browser.
In this tutorial, we learned three ways to hide an element using JavaScript. The first approach was to use the hidden property of an element. The next was to set style.display property to ‘hidden’. The third method was to set style.visibility property to ‘hidden’.
Показать и скрыть элемент на JS
На этом уроке вы узнаете, как на языке JavaScript показать и скрыть любой элемент на сайте, кликнув по кнопке.
HTML структура
В HTML разметке присутствует кнопка, имеющая начальное положение "Показать элемент" и скрытый текстовый блок. При клике по кнопке, блок с текстом показывается. При повторном клике по кнопке, данный блок скрывается. Зададим текстовому блоку класс content, отвечающий за оформление и класс hidden. Из названия последнего понятно, что этот класс скрывает контент, пока пользователь не сделает клик по кнопке.
Товарищи! постоянное информационно-пропагандистское обеспечение нашей деятельности влечет за собой процесс внедрения и модернизации дальнейших направлений развития. Повседневная практика показывает, что реализация намеченных плановых заданий обеспечивает широкому кругу (специалистов) участие в формировании новых предложений. CSS код
Разукрасим нашу кнопку линейным градиентом и установим легкую тень.
.btn text-decoration: none;
text-align: center;
width: 250px;
padding: 20px 0;
border: solid 1px #004F72;
border-radius: 4px;
font: 20px Arial, Helvetica, sans-serif;
font-weight: bold;
color: #E5FFFF;
background-color: #3BA4C7;
background-image: linear-gradient(top, #3BA4C7 0% ,#1982A5 100%);
box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
outline: none;
>
.content margin-top: 20px;
padding: 20px;
border: solid 1px rgb(214, 218, 219);
border-radius: 4px;
font-family: Calibri, 'Trebuchet MS', sans-serif;
>
.hidden display: none; // скрывает текст
>
JavaScript код
По событию клика по кнопке, у текстового блока должен удалиться класс hidden и тогда блок перестанет быть скрытым. Повторный же клик по кнопке наоборот вешает класс hidden на контентный блок, тем самым скрывая его. Как видите, весь механизм завязан на классе hidden.
Создадим две переменные, которым присвоим кнопку и блок по названиям селекторов. Затем будем отлавливаем событие клика по кнопке с помощью обработчика событий addEventListener. Первым параметром мы передаем событие клика, а вторым параметром название функции btnClick, в которой описываем действия, которые должны произойти после клика по кнопке. Первым делом необходимо найти класс hidden и при помощи метода toggle (переключатель) добавлять класс hidden, если его нет и удалять, если он есть. Кроме того на кнопке должны меняться надписи "Показать элемент / Скрыть элемент". Для этого обратимся к свойству кнопки textContent и создадим условие if-else. Если в блоке с классом content содержится и класс hidden, то поменять на кнопке надпись на "Скрыть элемент". В противном случае оставить, как было "Показать элемент".
const btn = document.querySelector(".btn");
const content = document.querySelector(".content");
function btnClick() console.log(content.classList);
if (content.classList.contains("hidden")) btn.textContent = "Скрыть элемент";
> else btn.textContent = "Показать элемент";
>
Демонстрация показа и скрытия элемента
Создано 17.04.2020 10:32:13
Михаил Русаков