12.2 JavaScript: JQuery and CSS

jQuery provides very easy implementation of CSS files to your html page. You can apply CSS on your whole page or on specific part of html.

jQuery with CSS file

First create a file style.css and copy following code in it and save this file on same place where you have all js and html files.

.mystyle {
  text-align: center;
  font-size: 25pt;

Open your html file and make sure that css file is included in html

<link rel="stylesheet" type="text/css" href="style.css" />

This is the continuation of your previous article so it is assumed the html and javaScript files are the same.

addClass(), Apply CSS by ID

jQuery addClass function helps to implement css style on your required tag. Provide tag id oh html and style from css file. “mystyle” is class name which you have created in your style.css file. Copy this line and add in your javaScript file.


Apply CSS by tag

You can apply CSS on similar tags. Implement CSS on all paragraphs of html.


Apply CSS on selected ids 

You can also implement CSS on selected tags.

$("#p2, #title").addClass('mystyle');

Apply CSS on specific text

Apply CSS on all paragraphs which contains text of your choice

$("p:contains('a Paragraph')").addClass('mystyle');

Apply CSS on next or previous tag, the tag which contains text of your choice

$("p:contains('Paragraph 2')").prev().addClass('mystyle');
$("p:contains('Paragraph 2')").next().addClass('mystyle');

you can also select siblings or parents as well

jQuery with HTML List

Add this list in your html file so you can see jQuery magic with list

  <li name="Blue">Blue</li>
  <li name="Red">Red</li>

Apply CSS on specific list item (1,2 or 3)


Apply CSS on next element


Apply CSS on without name elements


Continue with next article


Download file from GitHub