I have this code,everything works fine but .css('color','red') rule is not getting applied.I tried different ways but could’nt find any.
$('#menu li').each(function() {
$(this).hover(function() {
$(this).text().charAt(0).css('color','red');
});
});
But this code works fine.Cant figure what is wrong with above code.
$('#menu li').each(function() {
$(this).hover(function() {
$(this).css('color','red');
});
});
Thank you for your responses.
$(this).text().charAt(0)is a javascript string. It has no method.css().So, you can’t apply CSS to a single character in a javascript string.
If you want to apply a color to one character in the page, you’ll have to get the text, add a span tag around the first character, add style to that, then set that HTML back on the DOM element.
I’d suggest changing your code to this:
You can see that one in action here: http://jsfiddle.net/jfriend00/9xCak/
I would not recommend using this jQuery because there are much better ways to do this. It can be done with pure CSS or you could just add/remove a class with your jQuery.
Note, that you don’t need the
eachloop as you can just set a hover handler on the first jQuery selector and it will do .hover for all matched elements in the selector. Also, you have a second function in the hover call to set it back when the mouse leaves..If you intend for the red to go away when the mouse leaves the li, then you could do this entirely with CSS. No jQuery is required.
HTML:
CSS: