The <a>
inside the last <li>
of the innermost <ul>
has a class which is named current
. It highlights the active link.
I want to highlight all links that are parents from this link.
HTML
<ul>
<li>
<a href="a.html">Samsung</a>
<ul>
<li>
<a href="b.html">Galaxy</a>
<ul>
<li>
<a href="c.html">Galaxy Note 4</a>
</li>
<li>
<a href="c.html" class="current">Galaxy S 5</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
Galaxy S 5 has the class current
, but I also want to add the class current
to the parent links (Samsung, Galaxy).
答案 0 :(得分:0)
var els = document.getElementsByClassName('current')
for(var i = 0; i < els.length; i++) {
if(els[i].parentNode != null)
els[i].parentNode.className += ' current';
}
答案 1 :(得分:0)
HTML:
<ul>
<li>
<a href="a.html">Samsung</a>
<ul>
<li>
<a href="b.html">Galaxy</a>
<ul>
<li>
<a href="c.html">Galaxy Note 4</a>
</li>
<li>
<a href="c.html" id="s5">Galaxy S 5</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
JavaScript:
<script>
ele = document.getElementById("s5");
par1 = ele.parentNode.parentNode.parentNode;
par1.children[0].className+="current";
par2 = par1.parentNode.parentNode;
par2.children[0].className+="current";
</script>
我已经使用parentNode从最后的children.start中选择父元素。希望这对你有用。 :)
答案 2 :(得分:0)
内部class="current"
有六个父母。假设没有其他类以current
命名。
使用内部 节点并从那里转到外部 节点。将 parentNode 添加到当前节点。
node = node.parentNode
如上所述,那里有六个节点。
var count = 0;
var max = 6;
while(count < max) { ...; count += 1 }
检查节点名称是<li>
还是不内部<li>
。添加到第一个孩子,即<a>
班级名称。
if(node.nodeName === "LI") {
if(count > 1) {
node.children[0].className = "myClass";
}
}
// If there are no other classes that are named with "current"
// There are six parents from inside node
var node = document.getElementsByClassName("current")[0];
var count = 0;
var max = 6;
var cN = "current";
while (count < max) { // 6 times (ul li ul li ul li)
node = node.parentNode;
if (node.nodeName === "LI") {
if (count > 1) { // Not <li> inside
node.children[0].className = cN; // <a>
}
}
count += 1;
}
.current {
background: pink;
}
<ul>
<li>
<a href="a.html">Samsung</a>
<ul>
<li>
<a href="b.html">Galaxy</a>
<ul>
<li>
<a href="c.html">Galaxy Note 4</a>
</li>
<li>
<a href="c.html" class='current'>Galaxy S 5</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
答案 3 :(得分:0)
temp.parentNode
。如果元素父节点是列表项,则将当前类添加到列表元素的第一个子元素。
var until = document.getElementById("list"),
crnt = document.getElementsByClassName('current'),
tmp = crnt.item(0);
while(tmp !== until) {
if(tmp.tagName === "LI") {
tmp.children.item(0).classList.add("current");
}
tmp = tmp.parentNode;
}
.current {
color: tomato;
}
<ul id="list">
<li>
<a href="a.html">Samsung</a>
<ul>
<li>
<a href="b.html">Galaxy</a>
<ul>
<li>
<a href="c.html">Galaxy Note 4</a>
</li>
<li>
<a href="c.html" class="current">Galaxy S 5</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>