Lazerr Tag
Lazerr Tag

Reputation: 61

Javascript to hide an element based on the contents of an active-class element elsewhere

I'm trying to hide some elements on a page based on the contents of the specific element in a navbar (formed as a list) which has an active class. Here's what I've tried so far.

var element=document.querySelector('ul.nav > li.active')
if((typeof element != 'undefined')?element.innerText == "Page 1")
{
   document.getElementById("options1").style.display = 'none';

}

And the HTML that I need to work with is basically as follows.

<ul class="nav navbar-nav navbar-left">
 <li class="active">
  <a href="#section-page-1">Page 1</a>
 </li>
 <li>
  <a href="#section-page-2">Page 2</a>
 </li>
 <li>
  <a href="#section-page-3">Page 3</a>
 </li>
</ul>

<div id="options1">Stuff Here</div>

The behavior that I want is that when Page 1 is active, the <div> is hidden, and when all other pages are active, the <div> is visible.

I've tried a bunch of closely related things from stack overflow but haven't managed to get anything to work yet.

Thanks! I'm pretty new to javascript.

Upvotes: 0

Views: 47

Answers (1)

Theo
Theo

Reputation: 305

You can get the # called by your link with window.location.hash is JS like

if (window.location.hash === "#section-page-1") {
  document.getElementById("options1").style.display = 'none';
}

This should work

Upvotes: 1

Related Questions