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.
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>
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.
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.
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.