How can I do to surround the content between <h4>
and the next <h4>
within the main
element with <section>
tags, when the depth of the <h4>
elements varies? In example below, lines 3 to 5, lines 7 to 11, and lines 12 to 14 should be enclosed with <section>
tags respectively.
<main class="main">
<div class="styling-div"><h3>Main Heading 1</h3></div>
<h4>Subheading</h4>
<p>Text</p>
<img src="src">
<div class="styling-div"><div class="another-div"><h3>Main Heading 2</h3></div></div>
<h4>Subheading</h4>
<p>Text</p>
<div class="styling-div-for-h5"><h5>Sub-subheading</h5></div>
<p>Text</p>
<p>Text</p>
<div class="styling-div-for-h4"><h4>Subheading</h4></div>
<p>Text</p>
<figure>Image</figure>
</main>
I have no idea for placing tags responding properly.
2
Answers
What you need to do to wrap parts of main in sections that are started by h4 tags at varying depths is iterate through the children of the main tag.
By checking if each child either is or contains an h4 tag you know you need to insert a section element before it and insert the child into it. If the child does not meet the condition you just insert it into the section last created or just leave it be if no section has been created yet.
You can try:
Prints: