addClass to parent(LI)

一笑奈何 提交于 2019-12-03 08:25:53

Try

$(".filters-list li a").click(function (e) {
    e.preventDefault();
    $(".filters-list li").removeClass("selected");
    $(this).closest('li').addClass('selected'); // I also tried .parent().addClass
});

.closest() will get the first element that matches the selector.

I made a sample for you:

<script type="text/javascript" src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
    <style>
        .selected {font-weight:bold}
    </style>
    <ul class="filters-list">
        <li class="selected"><a href="#section1">About</a></li>
        <li><a href="#section2">Gallery Photos</a></li>
        <li><a href="#section3">Contact</a></li>
    </ul>

<script type="text/javascript">
$(document).ready(function(){
    $(document).on("click",".filters-list li a", function () {
        $(".filters-list li").removeClass("selected");
        $(this).parent().addClass("selected");
    });
});
</script>

Try this out:

$(this).parents("li:first").addClass('selected');

it could be that you are not selecting the target parent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!