Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
jQuery 2.0 Development Cookbook

You're reading from   jQuery 2.0 Development Cookbook As a web developer, you can benefit greatly from this book - whatever your skill level. Learn how to build dynamic modern websites using jQuery. Packed with recipes, it will quickly take you from beginner to expert.

Arrow left icon
Product type Paperback
Published in Feb 2014
Publisher Packt
ISBN-13 9781783280896
Length 410 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Leon Revill Leon Revill
Author Profile Icon Leon Revill
Leon Revill
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Document Object Model Manipulation FREE CHAPTER 2. Interacting with the User by Making Use of jQuery Events 3. Loading and Manipulating Dynamic Content with AJAX and JSON 4. Adding Attractive Visuals with jQuery Effects 5. Form Handling 6. User Interface 7. User Interface Animation 8. Understanding Plugin Development 9. jQuery UI 10. Working with jQuery Mobile Index

Selecting elements

There are many ways in which you can use jQuery to select DOM elements. We will explore the main methods here. For developers familiar with CSS, it is possible to use the same syntax when selecting elements with jQuery (that is, #content, .content, and so on).

Getting ready

Open a blank HTML document within your text editor or IDE of choice. Ensure that you have the latest version of jQuery downloaded and is easily accessible for inclusion into this HTML document. When creating new HTML files within this chapter, ensure that they are all within the same directory as the jQuery library file, making it easy to include into the HTML document.

How to do it…

To understand how you can use jQuery to select a variety of DOM elements, perform each of the following recipe steps:

  1. Create a web page using the following HTML and JavaScript code:
    <!DOCTYPE html>
    <html>
    <head>
       <title>Selecting Elements with jQuery</title>
       <script src="jquery.min.js"></script>
       <script>
          $(function(){
             var content = $("#content"); //Select the content div
             var span = $(".span-element"); //Select the span element
             var listelements = $("li"); //Select all the list elements
          });
       </script>
    </head>
    <body>
    <div class="division-container">Some text within a div which has a class</div>
    <div id="content">Some text within a div which has an ID attribute</div>
    <a href="#">A link</a>
    <a href="#" rel="dofollow">A second link</a>
    <ul class="info-list">
       <li>List Item 1</li>
       <li>List Item 2</li>
       <li>List Item 3</li>
    </ul>
    <button>Button 1</button>
    <span class="span-element">Span 1</span>
    </body>
    </html>
  2. To select any of these elements, use the jQuery's $() function. We can use this function in conjunction with an identifier or CSS selector for an element we would like to select; for example, its HTML tag li and ID #content or a class .content.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

How it works…

The simplest method of selecting a DOM element is by its ID. We know that all IDs within a HTML document should be unique; therefore, by selecting an element with its ID, you will be selecting a single element.

In reference to the preceding HTML document, if you wanted to select <div>, which has an ID content, you can use the following jQuery code to select it:

$(function(){
   var content = $('#content');
});

This would make the DOM element available within the content variable. More on what this means is covered later in the chapter.

Note

Any code within $(function(){ }); will be automatically executed by jQuery when the page is loaded.

We can also select elements in the same way using their class. The code is very similar to the preceding example, except that we use the class prefix (.) instead of the ID prefix (#), illustrated as follows:

$(function(){
   var span = $('.span-element');
});

Not only can we select elements based on some identifier we specify (that is, class or ID), but we can also select elements based on their tag name. If you wanted to select all the li elements within a page, you would use $('li'), illustrated as follows:

$(function(){
   var listelements = $('li');
   var i = 1;
   listelements.each(function(){
      console.log("Loop: " + i);
      i++;
   });
});

The preceding example uses the jQuery selector to select all the list elements within the page. To demonstrate that listelements now contains multiple elements, we loop through these and output some information to the console.

Note

.each() is a jQuery function. Learn more about its uses in Chapter 3, Loading and Manipulating Dynamic Content with AJAX and JSON.

The console output for the preceding example is as follows:

Loop: 1
Loop: 2
Loop: 3

Note

You can access the JavaScript console in various ways depending on your choice of browser:

  • Chrome: Ctrl + Shift + J (Mac: command + option + J)
  • Internet Explorer: F12
  • Firefox: Ctrl + Shift + K

There's more…

It is also possible to select elements based on other properties such as their rel or disabled attributes.

The following code shows us how we can select an anchor element that has a rel attribute of nofollow:

$(function(){
   var nofollow = $('a[rel="nofollow"]');
});

See also

  • Finding and selecting sibling elements
You have been reading a chapter from
jQuery 2.0 Development Cookbook
Published in: Feb 2014
Publisher: Packt
ISBN-13: 9781783280896
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image