Estoy buscando agregar números a los encabezados como a continuación. El problema es que hay documentos que pueden anidarse infinitamente y deben contarse de forma independiente. En el documento original, los encabezados son solo texto, sin prefijo numerado.
<div id="text_output"> <h1>Document 1</h1> <h2>1 Heading</h2> <h3>1.1 Subheading</h3> <h3>1.2 Subheading</h3> <div class="text_output_expansion"> <h1>Document 2</h1> <h2>1 Heading</h2> <h3>1.1 Subheading</h3> <h2>2 Heading</h2> <h3>2.1 Subheading</h3> </div> <h3>1.3 Subheading</h3> <h2>2 Heading</h2> <h3>2.1 Subheading</h3> <h3>2.2 Subheading</h3> <div class="text_output_expansion"> <h1>Document 3</h1> <h2>1 Heading</h2> <h3>1.1 Subheading</h3> <h2>2 Heading</h2> <h3>2.1 Subheading</h3> <div class="text_output_expansion"> <h1>Document 4</h1> <h2>1 Heading</h2> <h3>1.1 Subheading</h3> <h2>2 Heading</h2> <h3>2.1 Subheading</h3> </div> <h3>2.2 Subheading</h3> </div> <h3>2.3 Subheading</h3> <h2>3 Heading</h2> <h3>3.1 Subheading</h3> <h3>3.2 Subheading</h3> </div>Publicaré una solución CSS, pero estoy luchando para que esto funcione en javascript. La idea es que pueda copiar y pegar el documento con los números intactos (la solución CSS no lo permitirá). Es cierto que mi javascript no es excelente, pero mi lucha parece ser cómo js recorre los elementos de arriba a abajo.
Una solución es usar contadores CSS para agregar texto a los encabezados. Desafortunadamente, la debilidad (o fortaleza) de este enfoque es que es visible para el usuario, pero no se puede copiar y pegar desde el navegador, ni es fácil obtener el valor si lo necesita en otra parte de su secuencia de comandos.
#text_output { counter-reset: h2 } #text_output h2 { counter-reset: h3 } #text_output .text_output_expansion .card-body{ counter-reset: h2 } #text_output .text_output_expansion .card-body h2 { counter-reset: h3 } #text_output h2:before { counter-increment: h2; content: counter(h2) ". " } #text_output h3:before, h3.md-focus.md-heading:before { counter-increment: h3; content: counter(h2) "."counter(h3) ". " }Puede recorrer recursivamente la estructura agrupando en bloques de etiquetas h :
var div = document.createElement("div"); div.innerHTML = `<div id="text_output"> <h1>Document</h1> <h2>Heading</h2> <h3>Subheading</h3> <h3>Subheading</h3> <div class="text_output_expansion"> <h1>Document</h1> <h2>Heading</h2> <h3>Subheading</h3> <h2>Heading</h2> <h3>Subheading</h3> </div> <h3>Subheading</h3> <h2>Heading</h2> <h3>Subheading</h3> <h3>Subheading</h3> <div class="text_output_expansion"> <h1>Document</h1> <h2>Heading</h2> <h3>Subheading</h3> <h2>Heading</h2> <h3>Subheading</h3> <div class="text_output_expansion"> <h1>Document</h1> <h2>Heading</h2> <h3>Subheading</h3> <h2>Heading</h2> <h3>Subheading</h3> </div> <h3>Subheading</h3> </div> <h3>Subheading</h3> <h2>Heading</h2> <h3>Subheading</h3> <h3>Subheading</h3> </div>` document.querySelector('body').appendChild(div) function number_headings(root){ var h1 = 1; function label_headings(nodes, p){ var [groups, group, h] = [[], [], null] for (var i of nodes){ if (i.tagName[0].toLowerCase() != 'h' || (h != null && i.tagName != h.tagName)){ group.push(i) } else if (h === null){ h = i; } else{ groups.push({node:h, block:group.slice()}); group = []; h = i; } } if (h != null){ groups.push({node:h, block:group.slice()}); } var c = 1; for ({node:n, block:b} of groups){ if (n.tagName === 'H1'){ n.textContent = `${n.textContent} ${h1}`; h1++; } else{ n.textContent = `${(p === null ? c.toString() : p+'.'+c.toString())} ${n.textContent}`; } label_headings(b, n.tagName === 'H1' ? null : (p === null ? '':p+'.')+c.toString()); for (var k of b.filter(function(x){return x.nodeType === 1 && x.tagName[0] != "H"})){ label_headings(Array.from(k.childNodes).filter(function(x){return x.nodeType === 1}), null); } c++; } } label_headings(Array.from(root.childNodes).filter(function(x){return x.nodeType === 1})) } number_headings(document.querySelector('#text_output'), null)Hice otra opción recursiva. ¡Creo que Ajax tiene la mejor respuesta!
function numberHeadings(element) { var h1_counter = 0; var h2_counter = 0; var h3_counter = 0; var h4_counter = 0; var h5_counter = 0; var h6_counter = 0; element.find(".text_output_expansion").each(function () { numberHeadings($(this)); }); element.find("h1:not([numberHeadings=complete]),h2:not([numberHeadings=complete]),h3:not([numberHeadings=complete]),h4:not([numberHeadings=complete]),h5:not([numberHeadings=complete]),h6:not([numberHeadings=complete])").each(function () { switch ($(this).prop("tagName")) { case "H1": h1_counter += 1; h2_counter = 0; h3_counter = 0; h4_counter = 0; h5_counter = 0; h6_counter = 0; $(this).text(h1_counter.toString() + ". " + $(this).text()); $(this).attr("numberHeadings", "complete"); break; case "H2": h2_counter += 1; h3_counter = 0; h4_counter = 0; h5_counter = 0; h6_counter = 0; $(this).text(h1_counter.toString() + "." + h2_counter.toString() + ". " + $(this).text()); $(this).attr("numberHeadings", "complete"); break; case "H3": h3_counter += 1; h4_counter = 0; h5_counter = 0; h6_counter = 0; $(this).text(h1_counter.toString() + "." + h2_counter.toString() + "." + h3_counter.toString() + ". " + $(this).text()); $(this).attr("numberHeadings", "complete"); break; case "H4": h4_counter += 1; h5_counter = 0; h6_counter = 0; $(this).text(h1_counter.toString() + "." + h2_counter.toString() + "." + h3_counter.toString() + "." + h4_counter.toString() + ". " + $(this).text()); $(this).attr("numberHeadings", "complete"); break; case "H5": h5_counter += 1; h6_counter = 0; $(this).text(h1_counter.toString() + "." + h2_counter.toString() + "." + h3_counter.toString() + "." + h4_counter.toString() + "." + h5_counter.toString() + ". " + $(this).text()); $(this).attr("numberHeadings", "complete"); break; case "H6": h6_counter += 1; $(this).text(h1_counter.toString() + "." + h2_counter.toString() + "." + h3_counter.toString() + "." + h4_counter.toString() + "." + h5_counter.toString() + "." + h6_counter.toString() + ". " + $(this).text()); $(this).attr("numberHeadings", "complete"); break; } })};