![](/img/trans.png)
[英]jQuery addclass and removeclass in order from child to parent and reverse
[英]jQuery addClass of child to parent
我有http://jsfiddle.net/ShoeMaker/6EEjs/1/ ,看起来像:
<head><style>
span.mw-uctop {
font-weight: bold;
}
li.mw-uctop {
font-size: 8px;
text-decoration: italic;
}
</style><script>
$("li").contents("span.mw-uctop").addClass("mw-uctop");
</script></head><body>
<ul>
<li class="">Text blurb 1 <span class="mw-uctop">(top)</span> </li>
<li class="">Text blurb 2</li>
<li class="">Text blurb 3 <span class="mw-uctop">(top)</span> </li>
<li class="">Text blurb 4</li>
<li class="">Text blurb 5</li>
<li class="">Text blurb 6</li>
<li class="">Text blurb 7 <span class="mw-uctop">(top)</span> </li>
<li class="">Text blurb 8 <span class="mw-uctop">(top)</span> </li>
</ul>
</body>
我要寻找的最终结果是,我想将类“ mw-uctop”添加到所有具有“ mw-uctop”类的子级的“ li”元素中。 我该怎么做呢?
您可以这样做:
$('li > .mw-uctop').parent().addClass('mw-uctop');
如果用“孩子”来表示“后代”,则:
$("li:has(.mw-uctop)").addClass('mw-uctop');
如果您确实是个孩子,请尝试:
$("li:has(> .mw-uctop)").addClass('mw-uctop');
您可以尝试以下方法:
$('.mw-uctop').closest('li').addClass('mw-uctop');
只需尝试以下操作:
$('li').has('span.mw-uctop').addClass('mw-uctop');
这是一种更纯的面向JavaScript的方法:
var query = document.querySelectorAll('li > .mw-uctop');
//there are other workarounds for query selector for older browsers (ie6/7)
for(i=0;i<=query.length;i++){
query[i].parentNode.className+= 'mw-uctop';
// For Testing: document.write(query[i].parentNode.className+"<br>");
}
编辑:哎呀一秒钟编辑:固定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.