最小のオブジェクトのスタイルを変更する汎用ソリューションですが、その#content
すべてのサブ要素が表示されていることを確認するには#content
、の祖先を非表示にすることなく、各レベルのすべての兄弟をトラバースして非表示にするアルゴリズムが必要です#content
。これはで始まり、#content
上に行くため、内の要素を非表示にすることはありません#content
。
function hideAllExcept(id) {
var el = document.getElementById(id);
while (el && el != document.body) {
// go one level up
var parent = el.parentNode;
// get siblings of our ancesotr
var siblings = parent.childNodes;
// loop through the siblings of our ancestor, but skip out actual ancestor
for (var i = 0, len = siblings.length; i < len; i++) {
if (siblings[i] != el && siblings[i].nodeType == 1) {
// only operate on element nodes
siblings[i].style.display = "none";
}
}
el = parent;
}
}
hideAllExcept("content");
警告:この最初のバージョンでは、#contentの祖先の兄弟であるテキストノードは非表示になりません(親が非表示になっているため、#content以外の他のすべてのテキストノードは非表示になります)。これらのテキストノードも非表示にするには、<span>
タグにラップしてスタイルを設定できるようにする<span>
必要がありますが、OPがそのレベルの複雑さを必要とするのか、テキストノードをそのようにラップする必要があるのかはわかりません。
完全を期すために、親の兄弟テキストノードをラップして、に設定できるようにするバージョンを次に示しますdisplay: none
。これは、ソースHTMLに応じて、必要な場合と不要な場合があります。
function hideAllExcept(id) {
var el = document.getElementById(id);
while (el && el != document.body) {
// go one level up
var parent = el.parentNode;
// get siblings of our ancesotr
var siblings = parent.childNodes;
// loop through the siblings of our ancestor, but skip out actual ancestor
for (var i = 0, len = siblings.length; i < len; i++) {
var node = siblings[i];
if (node != el) {
if (node.nodeType == 1) {
// only operate on element nodes
node.style.display = "none";
} else if (node.nodeType == 3) {
// wrap text node in span object so we can hide it
var span = document.createElement("span");
span.style.display = "none";
span.className = "xwrap";
node.parentNode.insertBefore(span, node);
// Be wary of the dynamic siblings nodeList changing
// when we add nodes.
// It actually works here because we add one
// and remove one so the nodeList stays constant.
span.appendChild(node);
}
}
}
el = parent;
}
}
hideAllExcept("content");
そして実用的なデモ:http://jsfiddle.net/jfriend00/yVWDx/