const content = document.querySelector('.editer'),
htmlTags = content.getElementsByTagName("*");
let navs = [],
lastIndexH2 = 0,
lastIndexH3 = 0;
const addItem = (obj, elem) => {
obj.push({
name: elem.innerText,
id: elem.id,
children: []
});
}
htmlTags.forEach((e, i) => {
if (e.localName == 'h2') {
e.id = `nav-${i}`
addItem(navs, e);
lastIndexH2 = i;
}
else if (e.localName == 'h3') {
e.id = `nav-${i}`
const resH2 = navs.find(item => item.id == `nav-${lastIndexH2}`);
if (resH2) {
addItem(resH2.children, e);
lastIndexH3 = i
}
}
else if (e.localName == 'h4') {
e.id = `nav-${i}`
navs.find(itemH2 => {
if (itemH2.id == `nav-${lastIndexH2}`) {
const resH3 = itemH2.children.find(elem => elem.id == `nav-${lastIndexH3}`);
resH3 ? addItem(resH3.children, e) : addItem(itemH2.children, e)
}
});
}
});