I have a list in HTML with id of 'nav'. I want to apply CSS style to it using jQuery. How do I do it. I have tried couple of things and failed. Please help. I am new to jQuery and learning the basics now. thanks
-
What does your HTML markup look like and what have you tried so far that failed?FarligOpptreden– FarligOpptreden2012-02-08 12:47:46 +00:00Commented Feb 8, 2012 at 12:47
-
1Show us what you did and failed with. It's easier to help when we have code in front of us.Niklas– Niklas2012-02-08 12:48:10 +00:00Commented Feb 8, 2012 at 12:48
9 Answers
You can do the following:
$('li#nav').css('background','green');
$('li#nav') selects the list element. Then .css('background','green') applys green background to the li element.
Or you can do this:
Create a CSS class in your CSS file with a class
.list-style{
backbround : Green;
}
then in your jQuery write following:
$('li#nav').addClass('list-style');
Comments
Have you at least seen the manual? There are examples there: http://api.jquery.com/css/
1 Comment
Try this:
$(document).ready(function(){
/* Single style */
$('#nav').css('property','value');
/* Multiple styles */
$('#nav').css({'property1':'value1', 'property2':'value2', ...});
});
You can read more about CSS and Jquery here - http://api.jquery.com/css/
Comments
You can use the .css() jQuery function to get/set style rules to an element or a group of elements. Example:
$("#myDiv").css("display", "none");
$("input#myButton").css("background-color", "red");
Comments
Use the CSS method
$("#nav").css("color","red");
If you have a css class with some style definition, you may use the addClass method
$("#nav").addClass("myCSSStyle")
Working sample : http://jsfiddle.net/WRYKB/
HTML
<ul id="nav">
<li>One</li>
<li>Two</li>
</ul>
<ul id="nav2">
<li>One</li>
<li>Two</li>
</ul>
Javascript
$(function(){
$("#nav").css("color","red"); //setting css property to element
$("#nav2").addClass("myCSSStyle") //applying css class
});
CSS
.myCSSStyle
{
color:blue;
font-weight:bold;
}
Comments
You can add class to your nav like this
$("#nav").addClass("myClass yourClass");
For more info you can refer http://api.jquery.com/addClass/
Comments
This is not that hard ;)
HTML Code
<div id="navi" style="color: black">
HALLO
</div>
Javascript
$(document).ready(function() {
$("#navi").css("color", "red")
// Handler for .ready() called.
});