JQuery tutorial: apply styles


JQuery

Apply styles

To work with HTML elements, in JQuery you can select the elements and do some things on them by using the following prototype:
-Select by tag name:
$("tag-name").action();
-
Select by id:
$("#id").action();
-
Select by class name:
$(".class-name").action();



Example: In this example, we select the <p> paragraph elements by tag name and apply the same font color and width to the paragraphs using the css() function from the JQuery libary.
<html>
<head><title>Styling paragraph by tag name</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){

$("p").css({color: "green", width: "100px"});

});

</script>

</head>
<body>
<p> This is the first paragraph.</p>
<p> This is the second paragraph.</p>
</body>
</html>
 
Another example is to apply different color and width to different paragraphs by using the paragraphs ids.
<html>
<head><title>Styling paragraph by id</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){

$("#p1").css({color: "red", width: "100px"});
$("#p2").css({color: "green", width: "100px"});
});

</script>

</head>
<body>
<p id="p1"> This is the first paragraph.</p>
<p id="p2"> This is the second paragraph.</p>
</body>
</html>

Note: you can specify the #id after p like this:
$("p#p1").css({color: "red", width: "100px"});
$("p#p2").css({color: "green", width: "100px"});




Comments





This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.