I have an element "A", when I click on it, I want to change parent element's (LI
) class to selected
, but nothing changes...
$(".filters-list li a").click(function () {
$(".filters-list li").removeClass("selected");
$(this).parent('li').addClass('selected'); // I also tried .parent().addClass
});
Then I tried this code:
$(".filters-list li a").click(function () {
$(".filters-list li").removeClass("selected");
$(this).parent().get(0).addClass('selected'); // IE reports something like this: Object doesn't support addClass...
});
When I tried to define LI
with this code, it just reported me [Object HTMLLIElement]
:
alert($(this).parent().get(0));
What I'm doing wrong?
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
来源:https://stackoverflow.com/questions/19202076/addclass-to-parentli