[英]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.