Skip to content Skip to sidebar Skip to footer

Show All Div If None Of Link Clicked

I have a page name url.com/yourfirstpage/ when i go to the page all the div are hidden by default (display:none) if we target #sec1 as url.com/yourfirstpage/#sec1 it only displays

Solution 1:

Here is a trick in case you are able to modify your HTML structure. The idea is to have the elements visible and then we hide them using :target. Since we don't have previous sibling selector or parent selector, I used id within a parent element to be able to select any element:

#sec1:target.page:nth-child(n+2){
  display: none;
}

#sec2:target.page:nth-child(2n+1){
  display: none;
}

#sec3:target.page:nth-last-child(n+2){
  display: none;
}
<ahref="#sec1">sec1</a><ahref="#sec2">sec2</a><ahref="#sec3">sec3</a><divid="sec1"><divid="sec2"><divid="sec3"><divclass="page"> this is sec1</div><divclass="page"> this is sec2</div><divclass="page"> this is sec3</div></div></div></div>

It can work with any number of sections and we can improve the CSS code as follow:

#sec1:target.page:not(:nth-child(1)),
#sec2:target.page:not(:nth-child(2)),
#sec3:target.page:not(:nth-child(3)),
#sec4:target.page:not(:nth-child(4)),
#sec5:target.page:not(:nth-child(5)) {
  display: none;
}
<ahref="#sec1">sec1</a><ahref="#sec2">sec2</a><ahref="#sec3">sec3</a><ahref="#sec4">sec4</a><ahref="#sec5">sec5</a><divid="sec1"><divid="sec2"><divid="sec3"><divid="sec4"><divid="sec5"><divclass="page"> this is sec1</div><divclass="page"> this is sec2</div><divclass="page"> this is sec3</div><divclass="page"> this is sec4</div><divclass="page"> this is sec5</div></div></div></div></div></div>

Solution 2:

this quick approach may help

you can do with ! selector in CSS by using postcss plugins

[...document.querySelectorAll('a')].forEach(a => {
    a.addEventListener('click', () => {
        a.parentElement.classList.add('targeted')
    })
})
.targeteddiv {
  display: none;
}
.targeteddiv:target {
  display: block;
}
<ahref="#sec1">sec1</a><ahref="#sec2">sec2</a><ahref="#sec3">sec3</a><divid="sec1"class="page"> this is sec1</div><divid="sec2"class="page"> this is sec2</div><divid="sec3"class="page"> this is sec3</div>

Post a Comment for "Show All Div If None Of Link Clicked"