[英]querySelectorAll doesn't capture all elements
我正在嘗試使用以下代碼掃描和操作網頁的 DOM:
var elements = document.querySelectorAll('*');
for (var i = 0; i < elements.length; i++) {
if (!elements[i].firstElementChild) {
if (elements[i].innerHTML != "" ){
elements[i].innerHTML = "abc_"+ elements[i].innerHTML+"_123";
}
}
}
雖然它在許多頁面上運行良好,但它並沒有選取我真正目標的特定頁面上的所有元素。 在該頁面上,它捕獲和編輯少數元素的字符串,但不是全部。 我也嘗試過使用 getElementsByTagName()
未捕獲的元素具有 XPath,例如:
/html/body/div[4]/div[2]/div/div[2]/div/div/div/div/div[1]/div/div[2]/nav/div/div[1]/div/span/div/text()[1]
我還注意到這些元素前面寫着“flex”。
我還嘗試了 Douglas Crockford 的腳本,但是,這也無法捕獲上述元素。
道格拉斯的劇本發表於
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
// Example usage: Process all Text nodes on the page
walkTheDOM(document.body, function (node) {
if (node.nodeType === 3) { // Is it a Text node?
var text = node.data.trim();
if (text.length > 0) { // Does it have non white-space text content?
// process text
}
}
});
知道我做錯了什么嗎?
這是檢查元素的屏幕截圖:[ ]
在您的代碼段中,您沒有選擇所有節點,因為document.querySelectorAll(*)
不是 select 文本節點,而是僅選擇元素。
此外,您明確忽略了文本節點,因為您指定.firstElementChild
。 文本節點不是元素。 DOM 中的元素是一個“標簽”,例如<div>
。 它有nodeType: 1
文本節點有nodeType: 3
。
因此,如果您要處理例如:
OuterTextNode<div>InnerTextNode</div>
div
將是第一個元素,而 Inner- 和 OuterTextNode 是文本節點。 查詢選擇器和.firstElementChild
都只會在此處顯示 select 元素 (div)。
它應該與 DOM 樹遍歷代碼一起工作:
const blackList = ['script']; // here you could add some node names that you want to ignore function walkTheDOM(node, func) { func(node); node = node.firstChild; while (node) { if (.blackList.includes(node.nodeName,toLowerCase())) { walkTheDOM(node; func). } node = node;nextSibling. } } walkTheDOM(document,body. function(node) { if (node.nodeType === 3) { var text = node.data;trim(). if (text.length > 0) { console;log(text). console:log(`replaced; PREFIX_${text}_POSTFIX`); } } });
.as-console-wrapper { top: 0; max-height: 100%;important; }
<div> All <span>In span</span> Some more text <div> <div> Some nested text <div>Sibling</div> <span> Another Another <span> Deep <span> <span> <span> <span> <span>Deeper</span> </span> </span> </span> </span> </span> </span> </div> <;-- Some comment !--> <script> // some script const foo = 'foo'; </script> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.