Generate content based on text titles

Інше Mar 29, 2022
 Generate content based on text titles

Sometimes it is useful to show the content of a large article or text with the ability to quickly jump to a specific section.

A simple option is suitable for small texts: Just output.

Everything works quite simply.
We go through the whole text and find the titles there, we generate links for them so that we can navigate them later. We collect the titles in a separate block and at the end we insert it into the block specified in the settings.

const hlist = [];
let hNavigator = `<ul>`; // 
const listheadings = 'h1,h2,h3,h4,h5';
const selectorInsert = '.nav-text'; // селектор куда будем вставляти наш зміст
document.querySelectorAll(listheadings ).forEach((el, index) => {
            el.id = `it${index}`
            hNavigator += `<li><a class="${el.tagName}" href="#it${index}">${el.textContent}</a></li>`;
        })
hNavigator += `</ul>`
document.querySelector(selectorInsert).insertAdjacentHTML('beforeend', hNavigator)

Another option, already with the structure of attachments, can be styled as you see fit

function ListTOC(selectInsert){
  let hlist = [];
const listheadings = ['h1','h2','h3','h4','h5'];
const selectorInsert = selectInsert; // селектор куда будем вставляти наш зміст
let list = document.querySelectorAll(listheadings.join());

list.forEach((el, index) => {  
  const tagname = el.localName;
   hlist.push({
     'tagname':tagname,
     'index': index,
     'el':el
   });
}) 

let groups = hlist.reduce(function (r, a) {
        r[a.tagname] = r[a.tagname] || [];
        r[a.tagname].push(a);
        return r;
    }, Object.create(null));


let hNavigator = `<ul class="list-toc">`; 


for (el in groups){
   hNavigator += render(groups[el])
}

hNavigator += `</ul>`

document.querySelector(selectorInsert).insertAdjacentHTML('afterbegin', hNavigator)
/**
*/
function renderTocEl(el,index){
  return `<li class="${el.localName}"><a  href="#it${index}">${el.textContent}</a></li>`
}

function render(data){
let hNavigator = `<ul>`; 
  data.map(el=>{
    el.el.id = `it${el.index}` 
    hNavigator += renderTocEl(el.el,el.index);  
   })
   hNavigator += `</ul>`  
  return hNavigator;  
}
}

ListTOC('.main')

DEMO