POJS で、最新のブラウザー (ECMA5 と HTML5、IE10+ をサポート) のみを気にする
CSS
.hide {
display: none;
}
HTML
<input id="search"></input>
<div class="subjects">
<div class="subject">soccer</div>
<div class="subject">dancing</div>
<div class="subject">soap</div>
</div>
JavaScript
document.getElementById("search").addEventListener("keyup", function (evt) {
[].forEach.call(document.querySelectorAll(".subjects .subject"), function (subject) {
if (subject.textContent.indexOf(evt.target.value) === -1) {
subject.classList.add("hide");
} else {
subject.classList.remove("hide");
}
});
}, false);
jsfiddle
POJS およびクロスブラウザーが必要 (IE5.5 以降)
JavaScript
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
function classNameToArray(className) {
return className.split(/ +/);
}
function getElementsByClassName(node, className) {
var array = [],
elements = node.getElementsByTagName("*"),
elementsLength = elements.length,
i = 0,
element,
classNames,
classNamesLength,
x;
while (i < elementsLength) {
element = elements[i];
classNames = classNameToArray(element.className);
for (x = 0, classNamesLength = classNames.length; x < classNamesLength; x += 1) {
if (classNames[x] === className) {
array.push(element);
break;
}
}
i += 1;
}
return array;
}
document.getElementById("search").onkeyup = function (evt) {
var e = evt || window.event,
target = e.target || e.srcElement,
subjects = getElementsByClassName(document, "subjects"),
subject = [],
classnames,
classNamesLength,
classIndex,
element,
length,
index,
text;
for (index = 0, length = subjects.length; index < length; index += 1) {
subject = subject.concat(getElementsByClassName(subjects[index], "subject"));
}
for (index = 0, length = subject.length; index < length; index += 1) {
text = "";
element = subject[index];
walkTheDOM(element, function (currentNode) {
if (currentNode.nodeType === 3) {
text += currentNode.nodeValue;
}
});
classNames = classNameToArray(element.className);
for (classIndex = classNames.length - 1; classIndex >= 0; classIndex -= 1) {
if (classNames[classIndex] === "hide") {
classNames.splice(classIndex, 1);
}
}
if (text.indexOf(target.value) === -1) {
classNames.push("hide");
}
element.className = classNames.join(" ");
}
};
jsfiddle
または jQuery で (IE6+ または IE9+ は jQuery のバージョンによって異なります)
JavaScript
$("#search").keyup(function (evt) {
var subject = $(".subjects .subject");
subject.removeClass("hide");
subject.each(function (index, element) {
var $element = $(element);
if ($element.text().indexOf(evt.target.value) === -1) {
$element.addClass("hide");
}
});
});
jsfiddle
これらの例はすべて CSS を使用して div のスタイルを設定しているため、単に表示/非表示にするのではなく、境界線を強調表示または配置したい場合は、スタイルを簡単に変更できます。