<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 >....<span>...</span>...</p>我只需要 br 標簽的兒童標簽。我怎樣才能做到這一點。
最終輸出應如下所示:
Div 文本 lorem ipsum <br>lorem ipsum 段落內容<br>標簽和嵌套在其中的子項跨越內容
uj5u.com熱心網友回復:
如果您只想在任何元素中顯示文本,您可以使用innerText但您提到<br>在結果中需要標簽。所以你可以innerText先使用,然后\n用<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>
uj5u.com熱心網友回復:
您可以使用 JavaScript (while/for) 回圈。
這是一個活生生的例子。
顯示代碼片段
<!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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359550.html
標籤:javascript html 查询 dom
上一篇:如何在ReactonClick中洗掉和添加相同的事件偵聽器,以免它們無限疊加?
下一篇:如何在div框中顯示來自javascriptinnerhtml的文本輸出,而不會出現文本溢位和html/css樣式
