Home > OS >  Hide elements the correct way
Hide elements the correct way

Time:03-05

I'm using JavaScript to hide and show some elements onclick events

Using this code

function showPreOne() {
    document.getElementById('SecandModalFilter').classList.add('d-none');
    document.getElementById('FirstModalFilters').classList.add('d-none');
    document.getElementById('colocation').classList.add('d-none');
    document.getElementById('coloc-row').classList.add('d-none');
    document.getElementById('preFirstModalFilter').classList.remove('d-none');
    document.getElementById('FirstModalFiltersa').classList.add('d-none');
}

I don't think this is the correct way! ? specially if I have a very large page with a lot of tabs and elements ?

Thank you

CodePudding user response:

If the class is display: none, there's nothing wrong with that approach. Although the code would be more maintainable if you managed the add/remove elements with arrays of ids instead of doing it line by line.

CodePudding user response:

You could add a class on all the element that can be hidden (I assume you are handling a tab system), and just show the one you want to be visible:

function showPreOne() {
    document.querySelectorAll('.tab').forEach(elt => elt.classList.add('d-none'))
    document.querySelector('#SecandModalFilter').classList.remove('d-none');
}

Otherwise, your current method is not wrong per-say.

CodePudding user response:

Your approach can be a bit better, if you are showing/hiding elements I suggest you to use the toggle functionnality. This way you can use only one function that will manage your click event and hide/show your elements, just be sure that the initial state (d-none class present or not) is correct :

function showHide() {
    document.getElementById('SecandModalFilter').classList.toggle('d-none');
    document.getElementById('FirstModalFilters').classList.toggle('d-none');
    document.getElementById('colocation').classList.toggle('d-none');
    document.getElementById('coloc-row').classList.toggle('d-none');
    document.getElementById('preFirstModalFilter').classList.toggle('d-none');
    document.getElementById('FirstModalFiltersa').classList.toggle('d-none');
}

More informations here Toggle specification

  • Related