How can I use JQuery's addClass
method to add a class that has a space in it? For example:
.list {
padding-left: 0px;
margin-left: 20px;
}
.list li:hover {
background-color: AliceBlue;
}
I am trying to update/replace the inner html of a list inside an event handler, but when I do that all the CSS formatting goes away. I just need a way of putting it back, so I was going to use something like $('#my_list').addClass('list list li')
but I don't know how to get it to recognize the li
part. I've tried escaping the space, but no luck; passing it 'list list\\ li'
doesn't do the trick, either.
You only need to add the class list
to the #my_list
and rest of the code it just css. once you add the list
class to the ul
element, it will automatically apply the :hover
style for the child li
elements
jQuery,
$('#my_list').addClass('list');
css,
.list {
padding-left: 0px;
margin-left: 20px;
}
.list li:hover {
background-color: AliceBlue;
}
For more clear, in your code list
is the only class you has. and li
is not a class it is a li
element inside the ul
tag. and li:hover
means hover effect of the li
element
.list li
is not specifying a class with a space in it. That is selecting an li
element that is somewhere in the structure underneath any element with the list
class in it. It's hard to say exactly what you need to do without seeing how your HTML is structured and how much you're replacing. If you just replace the li
s inside of your .list
element then it will still work fine. If you're replacing the whole thing then just make sure you add the list
class to the parent element that contains the li
s.
The CSS selector .list li
matches the following:
Any
<li>
element that's a descendent of an element with the classlist
It does not match an element with a class called "list li"
. If you want to use some kind of spacer character in your classes use a hyphen:
.list-li:hover {
}
To add this class:
$(this).addClass('list-li')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.