Xpath tools: Difference between revisions

Jump to navigation Jump to search
758 bytes added ,  6 November 2024
Tags: Mobile edit Mobile web edit
Line 28: Line 28:


image hosted by [https://www.flickr.com/photos/planetoid/15103179455/ flickr]
image hosted by [https://www.flickr.com/photos/planetoid/15103179455/ flickr]
擷取指定 XPath 的元素文字,清理後以換行分隔顯示。下方例子的 XPath 規則是 {{kbd | key = <nowiki>//div[@id="showvender"]/a</nowiki>}}
<pre>
// 使用 document.evaluate 取得所有元素
const result = document.evaluate('//div[@id="showvender"]/a', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
// 建立陣列來存放所有元素的文字
const textArray = [];
// 遍歷所有元素
for (let i = 0; i < result.snapshotLength; i++) {
    const element = result.snapshotItem(i);
    // 去除換行符號並加入陣列
    const cleanedText = element.textContent.replace(/[\n\r]+/g, '').trim();
    textArray.push(cleanedText);
}
// 用換行符號連接所有元素
console.log(textArray.join('\n'));
</pre>


== chrome extension ==
== chrome extension ==

Navigation menu