私はプレーンな JavaScript の代替案を提供したいと考えました。これは (かなり) 改善される可能性があり、特にブール値を文字列として渡すこと (これは恐ろしいことです):
function hideByText(text, opts) {
if (!text) {
return false;
}
else {
var defaults = {
// the element we look within, expects:
// 1: node reference, eg the result of: document.getElementsByTagName('div')[0]
// 2: an element's id, as a string, eg: 'test'
'within': document.body,
// the element type, eg 'div', 'span', 'p', defaults to *everything*
'elemType': '*',
// case-sensitivity, as a string:
// 'true' : is case sensitive, 'Some' will not match 'some',
// 'false' : is case insensitive, 'Some' will match 'some'
'sensitive': 'true',
// 'absolute' : 'some text' will not match 'some text.'
// 'partial' : 'some text' will match 'some text.'
'match': 'absolute',
// 'true' : removes white-space from beginning, and end, of the text,
// 'false' : does not remove white-space
'trim': 'true',
// the class to add to elements if a match is made,
// use CSS to hide, or style, the matched elements
'matchedClass': 'hasText'
},
opts = opts || {};
for (var setting in defaults) {
if (defaults.hasOwnProperty(setting)) {
opts[setting] = opts[setting] || defaults[setting];
}
}
var within = opts.within.nodeType == 1 ? opts.within : document.getElementById(opts.within),
elems = within.getElementsByTagName(opts.elemType),
flags = opts.sensitive == 'true' ? 'i' : '',
needle = opts.trim == 'true' ? text.replace(/^(\s+) || (\s+)$/g, '') : text,
haystack,
reg = new RegExp(needle, flags);
if (opts.match == 'absolute') {
for (var i = 0, len = elems.length; i < len; i++) {
if ((elems[i].textContent || elems[i].innerText) == text) {
elems[i].className = opts.matchedClass;
}
}
}
else if (opts.match == 'partial') {
for (var i = 0, len = elems.length; i < len; i++) {
if ((elems[i].textContent || elems[i].innerText).match(reg)) {
elems[i].className = opts.matchedClass;
}
}
}
}
}
hideByText('some text', {
'match': 'partial',
'sensitive': 'true',
'elemType': 'p',
'matchedClass' : 'hasText'
});
JS フィドルのデモ。