繁体   English   中英

如何获取元素的html但忽略除br标签之外的子标签

[英]How to get html of element but ignoring children tags except br tag

<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>.

我想获取 div 元素的 html。 这是棘手的部分,如果我使用 .html() 这也将包括子标签,即<p class="some_class">....<span>...</span>...</p>我只需要br标签。 我怎样才能做到这一点。

最终输出应如下所示:

Div 文本 lorem ipsum <br> lorem ipsum 段落内容<br>标签和嵌套在其中的子项再次跨越内容

如果您只想在任何元素中显示文本,您可以使用innerText但您提到在结果中需要<br>标签。 所以你可以先使用innerText ,然后用<br>标签替换换行符( \\n )。

 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>

旧学校类型代码

像这样循环遍历字符

 <!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>

我刚刚为你写了一个代码如果它对你有用,我会很高兴。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM