Skip to content
Advertisement

Hide elements the correct way

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement