The code in the HTML I'm viewing appears as follows:
document.querySelectorAll('h4#unique_id ~ h5 ~p +p +h5').forEach(title => console.log(title))
<body>
<h4 id="unique_id"> foo bing bar </h4>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<!-- selection should start here -->
<h5>title text 1</h5>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<h5>title text 2</h5>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<h5>title text 3</h5>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<p>some text</p>
<!-- and end here -->
<h4 id="randome_id_234353">title text</h4>
<p>some text I don't want</p>
<p>some text I don't want</p>
<h5>title text I don't want</h5>
<p>some text I don't want</p>
<h5>title text I don't want</h5>
<p>some text I don't want</p>
<h5>title text I don't want</h5>
<p>some text I don't want</p>
</body>
I aim to extract all the h5
elements, along with the p
elements if possible.
My current attempt using
document.querySelectorAll('h4#unique_id ~ h5 ~p +p +h5')
misses the first desired h5
element and includes the last unwanted one. I am struggling with sibling selectors and how to utilize :not
or similar functions to halt when encountering another h4
.
This query is based on jquery which isn't accessible to me, while another solution assumes knowledge of the precise number and position of elements – something I lack. (Select elements between two defined elements)
Can this task be accomplished solely through CSS selectors?