简体   繁体   中英

Hide all elements within a class that don't match the ID of a variable

I have a site with tiles much like the Windows 10 Start menu.

I need these tiles to have fullwidth drop downs once clicked, I'll need the dropdown to close if the same tile is clicked again and I need one dropdown to close others if a different tile is clicked.

These tiles will have all sorts of names so I was hoping to create some javascript that would be dictated by the ID of the tile clicked.

Here's what I have so far:

<div id="gaming" class="box one-one blue" onclick="showSection(this);">
<div id="gaming-section" class="section">

<div id="marketing" class="box one-one blue" onclick="showSection(this);">
<div id="marketing-section" class="section">
function showSection(obj) {
    var tileName =obj.getAttribute('id');
    var sectionName =(tileName+'-section');
    document.getElementById(sectionName).style.display = "block";
}

Any help would be much appreciated

exchange document.getElementById(sectionName).style.display = "block"; for this:

const elemStyle = document.getElementById(sectionName);

if (elem.style.display !== 'block') {
    elem.style.display = 'block';
else {
    const elements = document.getElementsByClassName('section');
    elements.forEach(elem => {
        elem.style.display = 'none';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM