<div class="test"> Div Text lorem ipsum <br> lorem ipsum <p class="some_class">Paragraph Content <br> tag and again child nested in it <span> span content</span></p></div>. Quiero obtener html del elemento div. Aquí hay una parte complicada. Si uso .html(), esto también incluirá etiquetas para niños, que es <p class="some_class">....<span>...</span>...</p> I solo necesita la etiqueta br. ¿Cómo puedo lograr eso?
la salida final debería verse así:
Div Texto lorem ipsum <br> lorem ipsum Contenido de párrafo <br> etiqueta y nuevamente niño anidado en él abarca contenido
Si solo desea texto presente dentro de cualquier elemento, puede usar innerText pero mencionó que requería la etiqueta <br> en un resultado. Entonces puede usar innerText primero, luego reemplace el salto de línea ( \n ) con la etiqueta <br> .
var divtext = document.getElementsByClassName('test')[0].innerText; console.log(divtext); console.log(divtext.replaceAll('\n', '<br>')); <div class="test"> Div Text lorem ipsum <br> lorem ipsum <p class="some_class">Paragraph Content <br> tag and again child nested in it <span> span content</span></p></div>Puede usar un bucle JavaScript (while/for).
Aquí hay un ejemplo en vivo.
<!DOCTYPE html> <html lang="en"> <head> <title>Get Children Content with br tag</title> </head> <body> <div id="test"> Div Text lorem ipsum <br> lorem ipsum <p class="some_class">Paragraph Content <br> tag and again child nested in it <span> span content</span></p></div>. </body> <script> // get all the content of the div tag let test = document.getElementById("test"); let testData = test.innerHTML; let finalText = ""; // this variable will decide to capture the lettes when captured in loop. let capture = true; // starting to over all the cahracter in the text content for (let i = 0; i < testData.length; i++) { let recursive = false; if ( testData.charAt(i) == "<" && testData.charAt(i + 1) == "b" && testData.charAt(i + 2) == "r" ) { // if <br> tag is receved skip 4 char and increment the i value capture = true; recursive = true; } else if (testData.charAt(i) == "<") { // if < is found stop capturing capture = false; } else if (testData.charAt(i) == ">") { // if > is found start capturing but skip this iteration capture = true; } // main capturing code if (capture) { if (testData.charAt(i) != ">") { finalText = finalText + testData.charAt(i); } if (recursive) { finalText = finalText + testData.charAt(i + 1) + testData.charAt(i + 2) + testData.charAt(i + 3); i = i + 3; } } } console.log(finalText); </script> </html>