[英]How to replace all blank space with   while ignoring html tags
我將 div 元素中的所有空格替換為 這樣我就可以輕松地使用 JavaScript 文件讀取所有空格。 當我對此進行編碼時,我意識到 div 內的元素會變得混亂,因為像 ids 這樣的屬性需要標簽名稱之間的空格,並且屬性將被替換以破壞標簽。 我怎么能忽略標簽和名稱之間的空格而只替換文本空格。
代碼:
let el = document.getElementById('parent'); function replaceText() { let text = el.innerHTML.split(' ').join(' '); el.innerHTML = text; console.log(text); } //I dont want the span tag or em tag to get messed up by this
<!DOCTYPE html> <html> <body> <div id='parent'> Lorem ipsum <span id='element'> <em id='child'>dolor sit amet</em> </span> </div> <button onclick='replaceText()'>Change with nbsp</button> </body> </html>
我能想到的最好方法是在元素中查找文本節點。 您需要遞歸調用 function 直到沒有更多的文本節點。 下面是一些幫助您入門的示例代碼。
function replaceText(element) { for (let childNode of element.childNodes) { if (childNode.nodeType === Node.TEXT_NODE) { childNode.data = ' ' + childNode.data.trim().replace(/ /g, ' ') + ' ' continue } // Recursively replace text for child node replaceText(childNode) } }
<.DOCTYPE html> <html> <body> <div id='parent'> Lorem ipsum <span id='element'> <em id='child'>dolor sit amet</em> </span> </div> <button onclick='replaceText(document.getElementById("parent"))'>Change with nbsp</button> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.