with jQuery and having a wrapper container around the contents within each h1, I could easily hide them.
but with no wrapper container, how would one do it?
what's the best way to do something that just hides everything before the next h1?
I'm not using jQuery because this is part of a React app.
h1 {
border-bottom: solid 1px #000;
}
span {
float: right;
}
<h1>h1 <span>x</span></h1>
<p>test 1</p>
<h2>h2</h2>
<p>test 2</p>
<h1>h1-1 <span>x</span></h1>
<p>test 3</p>
<h2>h2-2</h2>
<p>test 4</p>
or wrap everything after and before the next h1 in a div tag?
You can hide an element in CSS using the CSS properties display: none or visibility: hidden . display: none removes the entire element from the page and mat affect the layout of the page. visibility: hidden hides the element while keeping the space the same.
Completely hiding elements can be done in 3 ways: via the CSS property display , e.g. display: none; via the CSS property visibility , e.g. visibility: hidden; via the HTML5 attribute hidden , e.g. <span hidden>
Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery. To hide an element, set the style display property to “none”.
I am able to do it with this css. Just add the class "start" to the h1 from which you want to start collapsing the elements and the class "upto" to the h1 upto which you want the elements to collapse.
CSS
.start ~ *:not(h1) {
display: none;
}
.upto ~ * {
display: block !important;
}
HTML
<h1 class='start'>h1 <span>x</span></h1>
...
<h1 class ='upto'>h1-1 <span>x</span></h1>
Here all the elements between start and upto will be hidden. You can have the collapse effect by placing adding the 'start' and 'upto' classes accordingly
The addition of the class to the next h1 could be also done via Javascript. So, I can have a simple js function which sets the 'start' and the 'upto'.
function collapse(startHeaderNumber, uptoHeaderNumber) {
var allHeaders = document.getElementsByTagName("h1");
var totalNoOfHeaders = allHeaders.length;
if (startHeaderNumber > totalNoOfHeaders) {
return;
}
var startHeader = allHeaders[startHeaderNumber - 1];
startHeader.classList.add('start');
if (uptoHeaderNumber <= totalNoOfHeaders) {
var uptoHeader = allHeaders[uptoHeaderNumber - 1];
uptoHeader.classList.add('upto');
}
}
And you can simply call it like
collapse(1 ,2)
And it would collapse all the items between headers 1 and 2. Or, you can call it like,
collapse(1)
which will collapse all elements from the first header till the last.
For a full demo, please see this fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With