Tengo un <div> con algunos niños dentro y contiene texto como el siguiente:
<div class="accordion-item__panel"> <h5>The baby tears the pages of the</h5> <p>books with her <span>hands.</span></p> <p class="body-small">What is the funniest thing the baby does?</p> </div> Quiero el texto contenido dentro del accordion-item__panel DIV y la salida como:
The baby tears the pages of the books with her hands. What is the funniest thing the baby does?Salida de corriente:
The baby tears the pages of the books with her hands. hands. What is the funniest thing the baby does?Se agregaron "manos". dos veces ya que se mantuvo dos veces al consultar elementos.
JavaScript:
let desc = ""; const descItems = item.querySelectorAll('.accordion-item__panel *'); descItems.forEach((item, index) => { if(index === 0){ desc += item.innerText; }else{ desc += ' ' + item.innerText; } }); console.log("desc", desc);Ejecuta esto:
let desc = ""; const descItems = document.querySelectorAll('.tcb__accordion-item__panel *'); descItems.forEach((item, index) => { if(index === 0){ desc += item.innerText; }else{ desc += ' ' + item.innerText; } }); console.log("desc", desc); .accordion-item__panel{ display:block; width: 300px; } .accordion-item__panel *{ padding: 0; margin: 0; } <div class="accordion-item__panel"> <h5>The baby tears the pages of the</h5> <p>books with her <span>hands.</span></p> <p class="body-small">What is the funniest thing the baby does?</p> </div>Simplemente puede seleccionar el elemento principal y acceder a la propiedad textContent . Concatenará efectivamente el contenido de los elementos secundarios en el formato que desee.
También podemos eliminar el exceso de espacios en blanco de los elementos secundarios que se separan mediante expresiones regulares y recortar los espacios en blanco iniciales/posteriores mediante el método trim cadenas.
const parentElement = document.querySelector('.accordion-item__panel'); console.log(parentElement.textContent); console.log(parentElement.textContent.replace(/\s{2,}/g, " ").trim()); <div class="accordion-item__panel"> <h5>The baby tears the pages of the</h5> <p>books with her <span>hands.</span></p> <p class="body-small">What is the funniest thing the baby does?</p> </div>textContent obtendría el texto sin formato sin etiquetas. Luego puede usar la función de reemplazo para eliminar los saltos de línea y múltiples espacios en blanco. Como eso:
const div = document.querySelector('div.accordion-item__panel'); console.log( div.textContent.replace(/(\r\n|\n|\r|\s{2,})/gm, "") ); <div class="accordion-item__panel"> <h5>The baby tears the pages of the</h5> <p>books with her <span>hands.</span></p> <p class="body-small">What is the funniest thing the baby does?</p> </div>