TL;DR
/**
* 条件に合ったコメントノードを取得します
* @license WTFPL
* @param {?string} pattern - ヒットさせる文字列
* @param {?Object} target - 検索するコンテキストノード
* @return {Array.<Object>} - テキストノードリスト
*/
const getTextNodes = (pattern, target) => {
const context = target ? ((d) => {
d.append(target.cloneNode(true));
return d
})(new Document()) : document;
const xPathResult = document.evaluate(
pattern ? `//text()[contains(., "${pattern}")]` : '//text()',
context,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
);
const result = [];
let {snapshotLength} = xPathResult;
while (snapshotLength--) {
result.unshift(xPathResult.snapshotItem(snapshotLength));
}
return result;
};
使用方法
const allTextNodes = getTextNodes(); // すべてのテキストノードを取得する
console.log(allTextNodes); // すべてのテキストノード
console.log(allTextNodes.length); // すべてのテキストノードの個数
console.log(allTextNodes[0].textContent);
allTextNodes[0].remove(); // 先頭のテキストノードを削除
console.log(allTextNodes('使用方法')); // コメントに「使用方法」を含むすべてのテキストノードを取得する
console.log(allTextNodes('', document.body)); // body 要素内のテキストノードをすべて取得する
console.log(allTextNodes('使用方法', document.body)); // コメントに「TODO」を含む body 要素内のテキストノードを取得する
テキストノードを検索する
JavaScriptで特定の文字列を含むコメントアウトを検索する方法(XPath)の余談記事です。
コメントノードが検索できるコードをテキストノードに置き換えたものです。
同じように検索したいノードタイプ別にXPATHを書き換えてあげればあらゆるノードが検索できます。