2

I have a page (/categories.html) with about 50 p elements :

<p id='BCI'>Blue_colored_items</p>
<p id='RCI'>Red_colored_items</p>
...

Now, I want the page to only show

Blue_colored_items

if

/categories.html#BCI

is the requested url, and so on.

How should I get that working? I can change the entire html.

Siamak
  • 335
  • 1
  • 11

3 Answers3

6

I just found this pure css working very well.

<style>
p {display: none}
:target {display: block}
</style>

Anyway, thanks for your answers, Rory and Andrei.

Siamak
  • 335
  • 1
  • 11
1
document.body.classList.add(window.location.hash.substring(1))

will add any existing hash as a class to your <body> element, allowing you control using CSS:

p {display:none;}
.BCI p#BCI {display: inline;}
.RCI p#RCI {display: inline;}
...

Or, you could simply search the <p> based on hash and display it:

// hardcoding hash for StackOverflow (only needed here, on SO):
window.location.hash = '#BCI';

let p = document.getElementById(window.location.hash.substring(1));
if (p) p.style.display = 'inline';
p { display: none; }
<p id='BCI'>Blue_colored_items</p>
<p id='RCI'>Red_colored_items</p>
tao
  • 82,996
  • 16
  • 114
  • 150
0

You can get the value from the window.location.hash property. Then you can hide the content you require excluding the specified element, something like this:

var hash = '#BCI'; // window.location.hash;

$('p').not(hash).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="BCI">Blue_colored_items</p>
<p id="RCI">Red_colored_items</p>

Note that p is a very generic selector I used only for this example. I'd suggest something much more specific for your production code.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339