Home > Software design >  Javascript - Hide all elements that do not have the specified ID
Javascript - Hide all elements that do not have the specified ID

Time:04-13

Hey there StackOverflow Community!

I'm fairly new to Stack and coding in general so this code will probably have an obvious error that I can't figure out.

Basically, in the following code I want everything shown on screen that isn't the element with the id settings to be hidden.

if ((!"#settings").style.display === "block") {
        $(!"#settings").hide();
    }

HTML:

<body>
    <span id="mainBtnArea">
        <button id="settings-btn">Settings</button>
        <button id="stats-btn">Stats</button>
    </span>
    <div id="mainArea">
        <h1 id="clickHeader"></h1>
        <button id="main-btn">Click Me</button>
    </div>
    <div id="settings">
        <h1>this is the page I want to show</h1>
    </div>
    <div id="stats">
        <p id="stats-clicks" >Keys:</p>
        <p id="stats-keys" >Keys:</p>
    </div>
</body>

CodePudding user response:

Query selectors don't work quite like that - you can't negate a selector with a ! symbol.

You can, however, use the visible selector and the not selector. The following will hide every visible element (:visible) that doesn't have the id x (:not('#x'))

 $(":visible:not('#x')").hide();

CodePudding user response:

var elements = document.getElementsByTagName('*');
for (var i = 0; i < elements.length; i  ) {
    if (elements[i].id != 'myId') {
        elements[i].style.display = 'none';
    }
}

You need to have a forloop!

  • Related