我必须修改 li 类“blackcat-21 wnode”,添加“active”,因为里面有一个与所选类的链接:
<a id="cat-21" href="" class="selected">link</a>
父“li”应该在“blockcat-21 wnode active”中改变。
<li class="blockcat-21 wnode">
<a id="cat-21" href="" class="selected">link</a>
<ul style="display: block;">
<li class="blockcat-33">
<a id="cat-33" href="" class="noselect" title="">link 2</a>
</li>
<li class="blockcat-22">
<a id="cat-33" href="" class="noselect" title="">link 2</a>
</li>
<li class="blockcat-34 last">
<a id="cat-34" href="" class="noselect" title=""></a>
</li>
</ul>
最佳答案
虽然不是太难的工作:
当所选 anchor 元素是 wnode
Vanilla
我们使用 document.querySelector
和选择器 a.selected
。这将搜索具有 selected
类的 anchor 元素。然后我们使用closest
来找到它。并使用 classlist
添加类。如果浏览器不支持 closest,我们可以使用 polyfill。
document.querySelector
returns the first child found. If you want to update more nodes that use brk's solution.
//using very modern browsers
if (Element.prototype.closest) {
document.querySelector("a.selected").closest(".wnode").classList.add("active");
}
//else
else {
//use the polyfill from MDN
if (!Element.prototype.matches)
Element.prototype.matches = Element.prototype.msMatchesSelector ||
Element.prototype.webkitMatchesSelector;
if (!Element.prototype.closest)
Element.prototype.closest = function(s) {
var el = this;
if (!document.documentElement.contains(el)) return null;
do {
if (el.matches(s)) return el;
el = el.parentElement;
} while (el !== null);
return null;
};
document.querySelector("a.selected").closest(".wnode").classList.add("active");
}
.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="blockcat-21 wnode">
<a id="cat-21" href="" class="selected">link</a>
<ul style="display: block;">
<li class="blockcat-33">
<a id="cat-33" href="" class="noselect" title="">link 2</a>
</li>
<li class="blockcat-22">
<a id="cat-33" href="" class="noselect" title="">link 2</a>
</li>
<li class="blockcat-34 last">
<a id="cat-34" href="" class="noselect" title="">link 2</a>
</li>
</ul>
</li>
使用 jQuery:
我们使用 a.selected
选择事件链接。我们可以在此处使用 jQuery 的 closest 来获取 wnode
祖先的 DOM 树。然后只需使用 addClass
和 viola。
$("a.selected").closest(".wnode").addClass("active");
.active{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="blockcat-21 wnode">
<a id="cat-21" href="" class="selected">link</a>
<ul style="display: block;">
<li class="blockcat-33">
<a id="cat-33" href="" class="noselect" title="">link 2</a>
</li>
<li class="blockcat-22">
<a id="cat-33" href="" class="noselect" title="">link 2</a>
</li>
<li class="blockcat-34 last">
<a id="cat-34" href="" class="noselect" title="">link 2</a>
</li>
</ul>
</li>
关于javascript - 根据子链接元素更改列表元素的父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46745792/