getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2019
getButterfly

How to hide an element using JavaScript

Here are 3 methods to hide an element using JavaScript.

Time needed: 1 minute.

How to hide an element using JavaScript?

  1. Set native display style to none

  2. Set CSS style property to none

    This method allows you to use other properties, such as opacity or visibility.

  3. Remove the element from the DOM

    This method is irreversible, as the element is completely gone. It needs to be added using another JavaScript action.

// Method #1
document.getElementById('element').style.display = 'none';

// Method #2
document.getElementById('element').style.setProperty('display', 'none', 'important');

// Method #3
document.getElementById('element').remove();

Also, here’s a collection of helper functions to automate showing and hiding elements:

var show = (elem) => {
    elem.style.display = 'block';
};
var hide = (elem) => {
    elem.style.display = 'none';
};
var toggle = (elem) => {
    // If the element is visible, hide it
    if (window.getComputedStyle(elem).display === 'block') {
        hide(elem);
        return;
    }

    // Otherwise, show it
    show(elem);
};

// Usage
show(document.getElementById('element'));
hide(document.querySelector('.element'));

Read more about arrow functions.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Thursday, August 22, 2019 in JavaScript

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

Related Articles

My Battle Tested Recommendations
Disclaimer: These recommendations contain affiliate links.

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush
SEMrush

Privacy Policy