jQuery Selecting Nodes Example


JQuery uses css selector and XPath to access elements in the Document Object Model (DOM). The returned object is Jquery object which we can further manipulate, for example, to bind events to these objects and add style to them, as well as chain multiple modifications together. In this example, we will see how to add style to the DOM elements using JQuery.

JQuery setup

Let’s look at the header part that has links to JQuery library, out style sheet and JQuery script we are going to use.

<script src="jquery.js"></script>
<script src="selectingElement.js"></script>
<link rel="stylesheet" href="selectingElement.css" type="text/css" />

The first statement loads the jQuery library. We are using jquery-2.1.4.js.
The next statement is used to link the javascript file selectingElement.js which will contain our JQuery functions. The third statement links the external style sheet file selectingElement.css.

$() function

We will use the $() function to access the DOM elements. This function accepts a CSS selector as its parameter and returns a new jQuery object pointing to the corresponding elements on the page.
To demonstrate the example, below is a simple html that has code>h2 element. We will use JQuery to add style to it dynamically once the page is loaded.

JQuery Selecting Nodes Example


<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>JQuery Selecting Elements Example</title>
<script src="jquery.js"></script>
<script src="selectingElement.js"></script>
<link rel="stylesheet" href="selectingElement.css" type="text/css" />
<h2>Selecting Elements</h2>
This is an example on JQuery Selecting Elements

Here is the style that we want to apply to our element.


.selection {
    background: #222;
    color: white;
    text-shadow: none;

Let’s look at the jquery function.


function() {

$('h2') selects all headings of level 2 in the document and applies class selection to them using addClass().
Now what about $(document).ready(..)?
This is used to delay the execution of javascript until the DOM is loaded. Remember the JavaScript file is referenced in the head section of the HTML file so will be executed first as soon the browser finds
the script line but the html elements used in the HTML file will not be loaded yet. A call to $(document).ready(..) to registers an event to be informed as soon as the DOM is ready. We create an anonymous function using the function keyword function(){...}, define the body of the function, and pass it to $(document).ready(..) so the function gets executed as soon as DOM is ready.

Run the example

JQuery Selecting Elements

JQuery Selecting Elements

Download the source code

This was an example about selecting elements using JQuery.

You can download the source code here: selectingElements.zip

Comments are closed.