JQuery Selectors

Selectors go inside the brackets; for example:

$(“div”)

The above code, will select all the div elements in your html (anything between

and

)

$(“div”).css(“background-color”,”red”);

The above code will select all the div elements, and change their background colour to red.

To select all paragraphs that are within (children of) div elements
$(“div > p“).css(“background-color”,”red”);

To select the first paragraph that is within (children of) div elements
$(“div > p:first-child“).css(“background-color”,”red”);

$(“div > p:first-child”).css(“background-color”,”red”);

P:odd will select on the odd paragraphs, e.g. the first, the third, the fifth paragraphs.

In the html
If you name a paragraph
i.e.
<p id=”drew”>This is drew’s paragraph</p>

This code will select the paragraph called “drew”.  The hashtag is the “ID selector”
$(“#drew“).css(“background-color”,”red”);

In the html name a class:
<p class=”Dave”>This is Dave’s paragraph</p>
This code will select the paragraph called “drew”.  The fullstop is the “class selector”

$(“.Dave“).css(“background-color”,”red”);

To make this a practical example

in the body of your html page, add a button:
<input id=”buttonOne” type=”button” value=”Go” />

Add some <divs> with some text and <p> paragraphs in between them.

Add the Google Jquery library at the end of the body of the html –

//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js

And add a link to the .js page:
http://drewCode.js

Create a new .js page called drewCode, and add the following code inside it:
$(document).ready(function() {
$(“#buttonOne”).click(function() {
$(“div”).css(“background-color”,”red”);
}0;
]);

 

References:
http://www.littlewebhut.com/javascript/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s