Introduction to JQuery - Selectors

Introduction to JQuery - Selectors

This article is supposed to be an introduction to JQuery. JQuery is a powerful Javascript library, which allows us to add impressive Javascript features to our web applications with very little coding. The most proper introduction in JQuery is learn about selectors.

The most proper introduction in JQuery is learn about selectors. To understand JQuery selectors you must have a basic knowledge of css(or HTML elements). First create an HTML file with the following and save it:

<html>
<head>
<title>Test page</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<p>Simple paragraph</p>
<p>Another simple paragraph</p>
<p id="idparagraph">Paragraph with id named idparagraph paragraph</p>
<p class="classparagraph">Paragraph with class named classparagraph paragraph</p>

<div id="mydiv">
<ul>
<li>list item1</li>
<li id="random-list-item">list item2</li>
<li>list item3</li>
</ul>
<p>Paragraph inside div</p>
<p class="classparagraph">Paragraph with class named classparagraph inside div</p>
</div>
<div id="second-div">
Text inside second-div
</div>

</body>
<html>

Usually when we use JQuery we follow this basic syntax:

$(selector).action()

We select through the selector one or more HTML elements and we perform some action on those selected elements. In order to understand the selectors we will use the simple .css JQuery method. With .css method we can set a CSS rule to some element. For example put the following lines just before the head tag closing.

<script>
	$(function() {
		$("p").css("color","red");
	});
</script>

In this case, our selector is "p", so we selected all paragraphs in our page. Refresh the browser. All paragraphs now must be red:

Lets say that we want all paragraphs with id=idparagraph to be red. Replace this

$("p").css("color","red");

with this:

$("#idparagraph").css("color","red");

Just the paragraph with id="idparagraph" will be red.

If we want 1) to paint green all the items in our list 2)to paint blue all text inside our divs or 3)underline paragraphs inside mydiv, we can write respectively:

$("li").css("color","#0f0");
$("div").css("color","#00f");
$("#mydiv p").css("text-decoration","underline");

 

I'm not going to show you an image for each one of these. It is really simple to copy-paste it and refresh your browser to see the result.
 
After all this reading you must understand what is a selector in JQuery. If so, experiment a little more by yourself. I am sure you will be more creative than me. If you think that all the above code was useless, you are right. We could style our page with CSS. It would be easier and better solution. However after this boring part (selectors), we can start creating something more interesting and useful with JQuery.

Add comment

* Name:
Website:
* Comment:
* Security code: