JQuery - Add css class to List
Question
I have the following HTML :
<li>
<a class="meuble-tab" href="#">Meuble</a>
</li>
i need to achieve the following:
<li class="active">
<a class="meuble-tab" href="#">Meuble</a>
</li>
Using Jquery I am at the point where i can get to the
$(".meuble-tab")
How do I get to its parent "li" to do the addClass("active")?
Solution
Try this:
$(".meuble-tab").parent("li").addClass("active");
For reference, please see parent( [expr] ):
Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements.
You may use an optional expression to filter the element(s). If there is no parent, returns a jQuery object with a length of 0.
OTHER TIPS
Complete Code :
===============
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("ul#unlist li").click(function(){
$("li").removeClass("tbg")
$(this).addClass("tbg");
});
});
</script>
<style>
.tbg{
background-color: green !important;
}
ul li{
display: inline;
padding:10px;
background-color:blue;
}
</style>
</head>
<body>
<ul id="unlist">
<li class="tbg"><a href="#">one</a></li>
<li><a href="#">two</a></li>
<li><a href="#">three</a></li>
<li><a href="#">four</a></li>
</ul>
</body>
</html>
Complete Code :
===============
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("li").click(function () {
var id = $(this).attr("id");
$('#' + id).siblings().find(".active").removeClass("active");
// ^ you forgot this
$('#' + id).addClass("active");
localStorage.setItem("selectedolditem", id);
});
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem != null) {
$('#' + selectedolditem).siblings().find(".active").removeClass("active");
// ^ you forgot this
$('#' + selectedolditem).addClass("active");
}
});
</script>
<style>
.active,.tbg{
background-color: green !important;
}
ul li{
display: inline;
padding:10px;
background-color:blue;
}
</style>
</head>
<body>
<ul id="unlist">
<ul id="unlist">
<li id="1" class="active"><a href="addcss.php">one</a></li>
<li id="2"><a href="addcss2.php">two</a></li>
<li id="3"><a href="addcss3.php">three</a></li>
<li id="4"><a href="addcss4.php">four</a></li>
</ul>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow