Override HTML element visibility controlled by a <details> tag

46 views Asked by At

I wanted to make an element inside a <details> tag be visible even if the <details> tag is not open using CSS styles. I tried using visibility, display, position, modifying the <details> tag height, etc. but nothing worked.

In this example I want the second paragraph to be visible even after closing the <details> tag:

<details>
  <summary>Category</summary>
  <p>A paragraph</p>
  <p> An another paragraph</p>
</details>

How could I achieve this? Is this possible to do without manipulating the DOM structure?

1

There are 1 answers

0
Mark Schultheiss On BEST ANSWER

NOTE: this DOES manipulate the DOM structure.

You cannot do this strictly with CSS that I know of however you can clone the paragraph and append it after the <details> element - might effect you style and you may need to account for that somehow.

Here is a verbose version of the script to show what it is doing. Note I added a class to the paragraph in the details to hide it always...

If this does not provide enough you might need to update something during the toggle event ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details#events

let details = document.querySelector('details');
let secondP = details.querySelector('p:last-of-type');
let clonedSecond = secondP.cloneNode(true);
secondP.classList.add('hide-me');
details.after(clonedSecond);
.hide-me {
  display: none;
}
<details>
  <summary>Category</summary>
  <p>A paragraph</p>
  <p> An another paragraph</p>
</details>