I want to create a tree using headers.
Example:
<h1>Wow</h1>
<h2>Blablablub</h2>
<p>Lorem Ipsum...</p>
<h1>Lalalala</h1>
<p>Lorem Ipsum...</p>
<h1>Ble</h1>
<h2>Test</h2>
<h3>Third</h3>
<p>Lorem Ipsum...</p>
This list should be created:
<ul>
<li>
<a>Wow</a>
<ul>
<li>
<a>Blablablub</a>
</li>
</ul>
</li>
<li>
<a>Lalalala</a>
</li>
<li>
<a>Ble</a>
<ul>
<li>
<a>Test</a>
<ul>
<li>
<a>Third</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
a tags should have a custom id but that isn't important for this question. I tried to do this but I couldn't figure it out. Here's what I tried:
function find_titles(find_num, element, prefix=""){
temp_list = $("<ul></ul>");
element.find(`${prefix}h${find_num}`).each(function(i, object){
let text = $(object).text();
let id = text.replace(/[^0-9a-zA-Z]/gi, "") + random_chars();
$(object).attr("id", id);
if ($(object).next().prop("tagName").toLowerCase() == `h${find_num + 1}`){
console.log($(object));
next_titles = find_titles(find_num + 1, $(object), "+ ")[0].innerHTML;
} else {
next_titles = "";
}
$(`<li><a href="#${id}">${text}</a>${next_titles}</li>`).appendTo(temp_list);
});
return temp_list;
}
EDIT
This:
<h1>First</h1>
<h2>Second</h2>
<p>Lorem Ipsum</p>
<h3>Third</h3>
Should be normally converted into this:
<ul>
<li>
<a>First</a>
<ul>
<li>
<a>Second</a>
</li>
</ul>
</li>
<li>
<a>Third</a>
</li>
</ul>
I don't care wether the first is a h1 h2 or a h3. In the text it's only important for styling but in the tree it isn't important.