A Beginner’s Guide to jQuery

• 8 minutes READ

Undoubtedly it’s the time of CSS. With the great support of current browsers almost everything seems possible just with it. Especially when you are lucky enough to code a mobile app and only have to consider WebKit as the browser. But often things are far from perfect and Internet Explorer 7 acts as the lowest common denominator. CSS is no option there to achieve great effects like sliders or similar. That’s when jQuery is glad to fill in. Although it consist of pure JavaScript and everything is also possible using it alone, jQuery is much easier to handle, learn and master. So sit back and follow me through this course of everything you have to know about jQuery to get started.

Let’s get started

The first thing to do is to integrate the jQuery script into the page. There are two ways to achieve that. The first option is to download the development version at https://jquery.com and run it locally.

<script type="text/javascript" src="jquery-1.7.2.js"></script>

You can also directly call it from a CDN (content delivery network) like Google Libraries API.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

The latter method has the advantage that you don’t have to download or setup anything and can start right away, which is perfect for a quick hack or if one wants to try out something. However in a production environment or if jQuery is planned to use throughout a project I suggest to go for the local version.

In either way insert the <script> tag at the end of the document, right before the closing </body> tag. This way jQuery doesn’t have to wait until the DOM (document object model = the structure of the website) is fully loaded; and things are a little bit faster this way. But if that’s no option for you of course there is also the possibility to paste it into the <head> tag. Unfortunately this has a big drawback. Since jQuery runs before everything else is loaded it has to wait for the readiness of the document thus the DOM’s entire availability. Therefore all of the jQuery statements have to be wrapped inside a function:

$(document).ready(function() {

You can also use a shorter version:

Online Email Template Builder

With Postcards you can create and edit email templates online without any coding skills! Includes more than 100 components to help you create custom emails templates faster than ever before.

Try FreeOther Products
$(function() {

Therefore, whenever possible, insert the script right at the bottom of the page.

The basics

The very basic part of jQuery is the selector:


It’s used to select any element in the DOM and manipulate it. $ here just functions a shortcut to jQuery, so you could also write jQuery('element').

Let’s say we have a website which only consists of a paragraph with some links within:

&lt;p&gt;Dismounting, I laid Powell upon the ground, but the most &lt;a href=&quot;#&quot;&gt;painstaking&lt;/a&gt; examination failed to reveal the faintest spark of life. I forced water from my canteen between his dead lips, &lt;a href=&quot;#&quot;&gt;bathed his face&lt;/a&gt; and rubbed his hands, working over him continuously for the better part of an hour in the face of the fact that I knew him to be &lt;a href=&quot;#&quot;&gt;dead&lt;/a&gt;.&lt;/p&gt;

For example to select every of the three links at a page write:


The result of this query is called a matched set, which in this case consists of all the links within the page, namely <a href="#">painstaking</a>, <a href="#">bathed his face</a> and <a href="#">dead</a>. This matched set can then  be further manipulated, like we will see later.

To actually see the result of this selection you can use the console of the browser Chrome. Just write console.log($('a')) at your script and then within the console all the selected links are shown and even highlighted in the page when you hover over them just like you know it from the well known option "Inspect element" or other CSS developer tools.

Create Websites with Our Online Builders

With Startup App and Slides App you can build unlimited websites using the online website editor which includes ready-made designed and coded elements, templates and themes.

Try Startup App Try Slides AppOther Products

Chrome’s console

One of the good things about jQuery is the tight linkage with CSS. Therefore you can use the jQuery selector to select elements on the page just like you would do it with CSS:

  • $('#elem') selects an element with the ID elem,
  • $('.myClass') selects an element with the class myClass,
  • and $('a, p') selects all links and paragraphs on the page at once.

Because of its deep relation with CSS you can also use the familiar pseudo-classes like :first-child, :nth-child or :last-of-type.

For example to select the second link on the page you can use:


But one has to be careful here; if the browser doesn’t support the pseudo-class it also doesn’t work in jQuery. Since one of the main goals of jQuery is browser in dependency there are numerous ways to achieve the same goal here. To select the second link just like above write:


Here jQuery reduces the set of matched elements (all the links) and only filters the second one. 1 instead of 2 is used here because CSS starts to count at 1, whereas for jQuery the first element conforms to 0.

Finally to get the first element use first(), for the last the method we have last().

Properties and attributes

Since we now know a great deal about how to select elements it’s time to actually do something with them. That’s when so called methods come into play. Just like with .eq() these methods are linked to the selector with a dot.

To change the color of the last link on the page to red write:

$('a').last().css('color', 'red');

Like you might already assume this css() method also allows to change all the other CSS properties of an element. To alter the font size one can write:

$('a').css('font-size', '20px');

To change multiple properties at one time you don’t have to do it separately but can combine it within a single method:

'font-size': '20px',
'background-color': 'blue',
'color': white

However three things are different than above:

  • The properties have to be wrapped in curly brackets
  • The property and the value are separated by a semicolon instead of a comma
  • Just like every declaration (property-value pair) must be separated by a comma

But instead of directly applying the CSS to the element it’s better to add a class:


This adds a class named highlight to the link. To remove a class in the same fashion the method removeClass() is used.

Just like many other methods the CSS method can not only be used to set properties but also to retrieve them. To get the current color of the link and save it to a variable:

var linkColor = $('a').css('color');

Furthermore there are also a few properties that have direct methods like $('a').width() and $('a').height(), which get the width or the height of the link. When a value is indicated the dimension can also be set: $('a').width('100') declares the width to be 100px. If you want to the height/width to include the padding and border the methods outerWidth() and outerHeight() are of particular interest.

Apart from this methods to manipulate the CSS properties of an element there is also the attr() method that is used to set/retrieve its attributes. For example there is the following input field:

&lt;input type=&quot;text&quot; placeholder=&quot;Username&quot;&gt;

To retrieve the placeholder attribute from it:


And to set it:

$('input').attr('placeholder', 'Your username');

To get the value of an form element there is also the shortcut method val().

Text manipulation

Another common task with jQuery is to change the text of an element. Let’s assume we have a paragraph with some strong text included:

&lt;p&gt;It is upon record, that &lt;strong&gt;three centuries&lt;/strong&gt; ago the tongue of the Right Whale was esteemed a great delicacy in France, and commanded large prices there.&lt;/p&gt;

To change the text of the strong part to “five years” we can write:

$('p strong').text('five years');

Because the text() method can only accept pure text there is also the html() method which can also handle HTML code too. To change the content of the strong tag from “three centuries” to “seven days” and additionally wrap the number within an <em> tag at the same time use:

$('p strong').html('&lt;em&gt;seven&lt;/em&gt; days');

The result then is: … record, that <strong><em>seven</em> days</strong> ago the tongue …

Just like with the css() method it’s also possible to retrieve a value instead of setting it. To store the text of the above-noted <em> tag into a variable called myText write:

var myText = $('p strong').text();

jQuery also enables to add content to elements, whereas there are two different approaches. With the methods prepend() and append() the content is added within the element’s tag. If we want to append “and more” inside the <strong> tag we can write:

$('p strong').append(' and more');

The result then is: … record, that <strong>three centuries and more</strong> ago the tongue …

To add some different text, let’s say “over” to this tag, but at the beginning, let’s write:

$('p strong').prepend('over ');

Result: … record, that <strong>over three centuries</strong> ago the tongue …

To add the content not within but outside the tag the methods before() and after() are available. For instance the result for $('p strong').after(' and more') is: … record, that <strong>three centuries</strong> and more ago the tongue …

The events to come

Unfortunately things are pretty static so far. jQuery offers a vast number of methods to manipulate elements, but its true strength lies within interactivity. To interact with elements so called event handlers are used. The perhaps simplest task is to click on an element. To do something at this event you can write:

$('button').on('click', function() {
	console.log(&quot;A click event has occurred&quot;);

Whenever a button on the page is clicked, the text “A click event has occurred” is outputted at the Chrome console. There are also other event types such as hover, focus, change (when a select box is changed), submit (when a form is submitted) and so on.

Sometimes you may also want to attach an event handler to a link, but instead of the standard behavior – namely to open the link – a method or the like should be performed. Example:

$('a#check').on('click', function(e) {
	$('p.alert').css('color', 'red');

When the link with the ID check is clicked the paragraph with the class alert becomes red.

You may remember the addClass() and removeClass() methods from above. In combination with event handlers a third and very similar method is getting very interesting, namely toggleClass().

$('button').on('click', function(e) {

Whenever the user clicks on the button, the <div> with the class box gets the additional class on. If it already has the class (for example it has already been clicked), then jQuery removes it.

But what if you want to address the element itself that has the event handler attached? For this purpose the $(this) selector comes into play, which represents the element which is currently interacted with. For example if you want to hide the button which currently was clicked you write:

$('button').on('click', function() {

I can (not) see you

Sometimes the task to execute is very simple: You just want to show or hide an element. jQuery offers two methods that do exactly that:

$('div.box').show() shows the <div> with the class box and $('div.box').hide() hides it. Finally we have toogle(), which works just like toggleClass(). In combination with event handlers it can hide or show elements based on their current status.

$('button').on('click', function() {

But to simply show or hide an element may sometimes be a bit harsh. Therefore there are also more subtle methods like fadeIn()/fadeOut() and slideIn()/SlideOut() respectively fadeToggle() and slideToogle(). The fade family changes the CSS’s opacity to hide/show the element and the slide family uses the element’s height for this purpose.

Up and down the tree

Based on the current position within the DOM (namely the selected element) there are several methods to move up and down the “tree” or to select certain elements. For a better understanding I’d like to describe them on the basics of the following HTML snippet:

&lt;header&gt;&lt;a href=&quot;https://designmodo.com&quot;&gt;Home&lt;/a&gt;
&lt;h2&gt;Choose a category&lt;/h2&gt;
	&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Design&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Graphics&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Inspiration&lt;/a&gt; &lt;strong&gt;Hot!&lt;/strong&gt;&lt;/li&gt;
	&lt;li class=&quot;last&quot;&gt;&lt;a href=&quot;#&quot;&gt;Freebies&lt;/a&gt;&lt;/li&gt;
&lt;a href=&quot;https://twitter.com&quot;&gt;Follow us on Twitter&lt;/a&gt;
&lt;a href=&quot;https://facebook.com&quot;&gt;Like us on Twitter&lt;/a&gt;

The selected element is the unordered list (<ul/>): $('nav ul')

$('nav ul').prev();

Selects the immediate preceding element at the same level: <h2>Choose a category</h2>

$('nav ul').next();

Selects the immediate following element at the same level: <a href="https://twitter.com">Follow us on Twitter</a>

$('nav ul').children();

Selects all children of the element:

	&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Design&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Graphics&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Inspiration&lt;/a&gt; &lt;strong&gt;Hot!&lt;/strong&gt;&lt;/li&gt;
	&lt;li class=&quot;last&quot;&gt;&lt;a href=&quot;#&quot;&gt;Freebies&lt;/a&gt;&lt;/li&gt;


$('nav ul').parent();

Selects the parent of the element: <nav> … </nav> (including everything within).

$('nav ul').parents('header');

By standard it selects all the parents of the element, therefore the <nav> … </nav>, the <header> … </header>, the <body> … </body> and <html> … </html> altogether and everything within them. But since we have stated an optional selector (header) only the <header> tag (and everything within it) is selected.

For the remaining methods to describe we have to select a different element: $('nav ul li').

$('nav ul li').siblings();

Selects all the elements at the same level, including the currently selected:

	&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Design&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Graphics&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Inspiration&lt;/a&gt; &lt;strong&gt;Hot!&lt;/strong&gt;&lt;/li&gt;
	&lt;li class=&quot;last&quot;&gt;&lt;a href=&quot;#&quot;&gt;Freebies&lt;/a&gt;&lt;/li&gt;


$('nav ul li').has('b');

Selects just the elements that matches the stated selector. Since only the third list item contains a <b> tag only this one is selected: <li><a href="#">Inspiration</a> <b>Hot!</b></li>

$('nav ul li').not('.last');

Select all elements but not the one with the class last: <li><a href="#">Design</a></li> <li><a href="#">Graphics</a></li> <li><a href="#">Inspiration</a> <b>Hot!</b></li>

Finally there is a method called each() that enables to loop through all the elements in the set of matched elements:

$('nav ul li').each(function(index) {
    $(this).append(' Item No.' + index);

For every list item a function is executed, which adds the index number of the current item at the end (beginning at 0). A roundup of the related methods can be found at https://api.jquery.com/category/traversing.

All of these methods – just like all of jQuery’s methods – can be combined into a single line, which is called chaining. Say we first want to give the currently selected element, the <ul>, a class called hover and then make all its children, the list items (<li/>s), bold:

$('nav ul').addClass('hover').children().css('font-weight', &quot;bold&quot;);

Just the beginning

For a beginner’s guide we have already covered pretty much in this lesson. Even so that was just the tip of the iceberg. jQuery is very powerful by all means and there are tons of topics to learn. If you have tasted blood and want to dig deeper into this language I really recommend you to take the free Tuts+ course called “jQuery in 30 days“. Almost everything I know about jQuery is coming straight from there.

Text courtesy of Fillerati: Edgar Rice Burroughs, “A Princess of Mars” and Herman Melville, “Moby Dick”.

Christian Krammer

Christian Krammer is web designer at one of Austria's biggest Newspaper called "Kleine Zeitung" where he works for over ten years.

Posts by Christian Krammer
Never miss an article or news again.

Sign up to get fresh stuff in your email monthly. For those who want to keep in touch with web design and development trends and tools.

Learn More About Newsletter
Cookie Icon

We use cookies to ensure that we give you the best experience on our website. Privacy Statement.

  • I disagree
  • I agree