頁面結構不可控、無 ID/Class,需精確定位特定標簽並設置 style.display = 'none'。
getElementsByTagName / querySelectorAll | 頁面唯一該標簽,或第 N 個 | document.getElementsByTagName('iframe')[0] |
| **屬性選擇器** | querySelectorAll('[attr=value]') | 元素有唯一屬性 (name, data-*, type) | document.querySelector('[name="csrf_token"]') |
| **樹關係** | parentNode.children[n], previousElementSibling | 相對於已知元素定位 | document.querySelector('h1').nextElementSibling |
| **XPath** | document.evaluate | 複雜結構、文字內容定位 | //div[contains(text(),'登錄')]/following-sibling::input |
| **TreeWalker** | document.createTreeWalker | 高性能遍歷過濾 | 遍歷所有文本節點查找關鍵字 |
| **文本內容** | 遍歷 + textContent.includes | 唯一標識是可見文字 | 查找包含「提交」的按鈕 |
// 找到 type=submit 且無 id/class 的按鈕
const btn = document.querySelector('button[type="submit"]:not([id]):not([class])');
if (btn) btn.style.display = 'none';
// 某個已知容器下的第 3 個 div
const container = document.getElementById('known-container'); // 假設容器有 ID
const target = container.querySelector('div:nth-of-type(3)');
function getElementByXPath(xpath) {
return document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
// 隱藏包含「廣告」文字的 div
const adDiv = getElementByXPath('//div[contains(., "廣告")]');
if (adDiv) adDiv.style.display = 'none';
function hideElementByText(text, tag = '*') {
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
let node;
while (node = walker.nextNode()) {
if (node.tagName.toLowerCase() === tag.toLowerCase() || tag === '*') {
if (node.textContent.includes(text)) {
node.style.display = 'none';
return node; // 找到第一個即返回
}
}
}
return null;
}
hideElementByText('關閉', 'button');
[name=...], [data-id=...]) —— 語義明確、性能好。nth-child, sibling) —— 相對穩定。getElementsByTagName 後手動循環遍歷,代碼冗長且易出錯。若頁面由框架 (React/Vue) 渲染,DOM 結構可能異步變化,建議在 MutationObserver 或框架生命週期 (onMounted) 中執行查找邏輯。