jQuery Introduction

The purpose of jQuery is to make it much easier to use JavaScript on your website.

What You Should Already Know

Before you start studying jQuery, you should have a basic knowledge of:

  • HTML
  • CSS
  • JavaScript

What is jQuery?

·        jQuery is a lightweight, "write less, do more", JavaScript library.

·        The purpose of jQuery is to make it much easier to use JavaScript on your website.

·        jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

·        jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

·        The jQuery library contains the following features:

 

ü  HTML/DOM manipulation

ü  CSS manipulation

ü  HTML event methods

ü  Effects and animations

ü  AJAX

ü  Utilities

Why jQuery?

·        There are lots of other JavaScript frameworks out there, but jQuery seems to be the most popular, and also the most extendable.

·        Many of the biggest companies on the Web use jQuery, such as:

ü  Google

ü  Microsoft

ü  IBM

ü  Netflix


jQuery Get Started

Adding jQuery to Your Web Pages

There are several ways to start using jQuery on your web site. You can:

  • Download the jQuery library from jQuery.com
  • Include jQuery from a CDN, like Google

Downloading jQuery

There are two versions of jQuery available for downloading:

  • Production version - this is for your live website because it has been minified and compressed
  • Development version - this is for testing and development (uncompressed and readable code)

Both versions can be downloaded from jQuery.com.

The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice that the <script> tag should be inside the <head> section):

<head>
<script src="jquery-1.12.0.min.js"></script>
</head>

jQuery CDN

If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network).

Both Google and Microsoft host jQuery.

To use jQuery from Google or Microsoft, use one of the following:

 

Google CDN:

 

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>

Microsoft CDN:

<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script>
</head>


 

jQuery Syntax

·        With jQuery you select (query) HTML elements and perform "actions" on them.

·       The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).

Basic syntax is: $(selector).action()

  • A $ sign to define/access jQuery
  • A (selector) to "query (or find)" HTML elements
  • A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

The Document Ready Event

·       You might have noticed that all jQuery methods in our examples, are inside a document ready event:

$(document).ready(function(){

   // jQuery methods go here...

});

·        This is to prevent any jQuery code from running before the document is finished loading (is ready).

·        It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.

·        Here are some examples of actions that can fail if methods are run before the document is fully loaded:

ü  Trying to hide an element that is not created yet

ü  Trying to get the size of an image that is not loaded yet

·       There is even a shorter method for the document ready event:

$(function(){


   // jQuery methods go here...
});

·       Any of the method can be used.


jQuery Selectors

·       jQuery selectors allow you to select and manipulate HTML element(s).

·       jQuery selectors are used to "find" (or select) HTML elements based on their id, classes, types, attributes, values of attributes and much more.

·       All selectors in jQuery start with the dollar sign and parentheses: $().

The element Selector

·       The jQuery element selector selects elements based on the element name.

·       You can select all <p> elements on a page like this:

 

$("p")

Example

·       When a user clicks on a button, all <p> elements will be hidden:

 

$(document).ready(function(){
    $("button").click(function(){
        $("p").hide();
    });
});

The #id Selector

·       The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

·       An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

·       To find an element with a specific id, write a hash character, followed by the id of the HTML element:

$("#test")

Example

·       When a user clicks on a button, the element with id="test" will be hidden:

$(document).ready(function(){
    $("button").click(function(){
        $("#test").hide();
    });
});

The .class Selector

·       The jQuery class selector finds elements with a specific class.

·       To find elements with a specific class, write a period character, followed by the name of the class:

$(".test")

Example

·       When a user clicks on a button, the element with class="test" will be hidden

$(document).ready(function(){
    $("button").click(function(){
        $(".test").hide();
    });
});

 

More Examples of jQuery Selectors

Syntax

Description

$("*")

Selects all elements

$(this)

Selects the current HTML element

$("p.intro")

Selects all <p> elements with class="intro"

$("p:first")

Selects the first <p> element

$("ul li:first")

Selects the first <li> element of the first <ul>

$("ul li:first-child")

Selects the first <li> element of every <ul>

$("[href]")

Selects all elements with an href attribute

$("a[target='_blank']")

Selects all <a> elements with a target attribute value equal to "_blank"

$("a[target!='_blank']")

Selects all <a> elements without a target attribute value NOT equal to "_blank"

$(":button")

Selects all <button> elements and <input> elements of type="button"

$("tr:even")

Selects all even <tr> elements

$("tr:odd")

Selects all odd <tr> elements

 

 

Functions In a Separate File

If your website contains a lot of pages, and you want your jQuery functions to be easy to maintain, you can put your jQuery functions in a separate .js file.

When we demonstrate jQuery in this tutorial, the functions are added directly into the <head> section. However, sometimes it is preferable to place them in a separate file, like this (use the src attribute to refer to the .js file):

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
</script>
<script src="my_jquery_functions.js"></script>
</head>


jQuery Event Methods

  • jQuery is tailor-made to respond to events in an HTML page.

What are Events?

·        All the different visitor's actions that a web page can respond to are called events.

·        An event represents the precise moment when something happens.

·        Examples:

ü  moving a mouse over an element

ü  selecting a radio button

ü  clicking on an element

·        The term "fires/fired" is often used with events. Example: "The keypress event is fired, the moment you press a key".

·        Here are some common DOM events:

·         

Mouse Events

Keyboard Events

Form Events

Document/Window Events

click

keypress

submit

load

dblclick

keydown

change

resize

mouseenter

keyup

focus

scroll

mouseleave

 

blur

unload

 

jQuery Syntax For Event Methods

·       In jQuery, most DOM events have an equivalent jQuery method.

·       To assign a click event to all paragraphs on a page, you can do this:

$("p").click();

·       The next step is to define what should happen when the event fires. You must pass a function to the event:

$("p").click(function(){
  // action goes here!!
});

 

 

 

Example :

When a click event fires on a <p> element; hide the current <p> element

 

 

<html>

<head>

<script src="jquery-2.1.4.js"></script>

<script>

$(document).ready(function(){

    $("p").click(function(){

        $(this).hide();

    });

});

</script>

</head>

<body>

 

<p>If you click on me, I will disappear.</p>

<p>Click me away!</p>

<p>Click me too!</p>

 

</body>

</html>

dblclick()

The dblclick() method attaches an event handler function to an HTML element.

mouseenter()

The mouseenter() method attaches an event handler function to an HTML element.

mouseleave()

The mouseleave() method attaches an event handler function to an HTML element.

mousedown()

The mousedown() method attaches an event handler function to an HTML element.

mouseup()

The mouseup() method attaches an event handler function to an HTML element.

hover()

The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods.

focus()

The focus() method attaches an event handler function to an HTML form field.

blur()

The blur() method attaches an event handler function to an HTML form field.

The on() Method

The on() method attaches one or more event handlers for the selected elements.


jQuery Effects

jQuery hide() , show() & toggle()

·        You can hide and show HTML elements with the hide() and show() methods:

·        You can toggle between the hide() and show() methods with the toggle() method.

·       Syntax:

$(selector).hide(speed,callback);
$(selector).show(speed,callback);

$(selector).toggle(speed,callback);

·       The optional speed parameter specifies the speed of the hiding/showing, and can take the following values: "slow", "fast", or milliseconds.

  • The optional callback parameter is a function to be executed after the hide() or show() or toggle() method completes.

·       Example:

$("#hide").click(function(){
    $("p").hide();
});

$("#show").click(function(){
    $("p").show();
});

$("button").click(function(){
    $("p").toggle();
});


jQuery Fading Methods

  • With jQuery you can fade an element in and out of visibility.
  • jQuery has the following fade methods:

o   fadeIn()

o   fadeOut()

o   fadeToggle()

o   fadeTo()

·       Syntax:

$(selector).fadeIn(speed,callback);
$(selector).fadeOut(speed,callback);

$(selector).fadeToggle(speed,callback);

$(selector).fadeTo(speed,opacity,callback);

  • The required speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.
  • The required opacity parameter in the fadeTo() method specifies fading to a given opacity (value between 0 and 1).
  • The optional callback parameter is a function to be executed after the function completes.

·       Example:

$("button").click(function(){
    $("#div1").fadeIn();
    $("#div2").fadeIn("slow");
    $("#div3").fadeIn(3000);
});

 

$("button").click(function(){
    $("#div1").fadeOut();
    $("#div2").fadeOut("slow");
    $("#div3").fadeOut(3000);
});

 

$("button").click(function(){
    $("#div1").fadeToggle();
    $("#div2").fadeToggle("slow");
    $("#div3").fadeToggle(3000);
});

 

$("button").click(function(){
    $("#div1").fadeTo("slow", 0.15);
    $("#div2").fadeTo("slow", 0.4);
    $("#div3").fadeTo("slow", 0.7);
});

 

 


jQuery Sliding Methods

  • With jQuery you can create a sliding effect on elements.
  • jQuery has the following slide methods:
    • slideDown()
    • slideUp()
    • slideToggle(

·       Syntax:

$(selector).slideDown(speed,callback);
$(selector).slideUp(speed,callback);

$(selector).slideToggle(speed,callback);

·       The optional speed parameter specifies the speed of the hiding/showing, and can take the following values: "slow", "fast", or milliseconds.

·       The optional callback parameter is a function to be executed after the sliding completes.

·       Example:

<html>

<head>

<script src="jquery-2.1.4.js"></script>

<script>

$(document).ready(function(){

    $("#flip").click(function(){

    $("#panel").slideToggle("slow");

    });

});

</script>

<style>

#panel, #flip {

    padding: 5px;

    text-align: center;

    background-color: #e5eecc;

    border: solid 1px #c3c3c3;

}

#panel {

    padding: 50px;

    display : none;

}

</style>

</head>

<body>

 <div id="flip">Click to slide the panel down and up </div>

 <div id="panel">Hello world!</div>

</body>

</html>


jQuery Animations - The animate() Method

  • The jQuery animate() method is used to create custom animations.

Syntax:

$(selector).animate({params},speed,callback);

  • The required params parameter defines the CSS properties to be animated.
  • The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.
  • The optional callback parameter is a function to be executed after the animation completes.

·       Example:  The following example demonstrates a simple use of the animate() method; it moves a <div> element to the right, until it has reached a left property of 250px:

<html>

<head>

<script src="jquery-2.1.4.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

                $("div").animate({left: '250px' });

    });

});

</script>

</head>

<body>

 

<button>Start Animation</button>

 

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

 

<div style="background:green;height:100px;width:100px;position:absolute;"></div>

 

</body>

</html>


jQuery stop() Method

  • The jQuery stop() method is used to stop an animation or effect before it is finished.
  • The stop() method works for all jQuery effect functions, including sliding, fading and custom animations.

Syntax:

$(selector).stop(stopAll,goToEnd);

  • The optional stopAll parameter specifies whether also the animation queue should be cleared or not. Default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards.
  • The optional goToEnd parameter specifies whether or not to complete the current animation immediately. Default is false.
  • So, by default, the stop() method kills the current animation being performed on the selected element.
  • Example: The following example demonstrates the stop() method, with no parameters: <html>

<head>

<script src="jquery-2.1.4.js"></script>

<script>

$(document).ready(function(){

    $("#flip").click(function(){

        $("#panel").slideDown(5000);

    });

    $("#stop").click(function(){

        $("#panel").stop();

    });

});

</script>

<style>

#panel, #flip {

    padding: 5px;

    font-size: 18px;

    text-align: center;

    background-color: #555;

    color: white;

}

#panel {

    padding: 50px;

    display: none;

}

</style>

</head>

<body>

<button id="stop">Stop sliding</button>

<div id="flip">Click to slide down panel</div>

<div id="panel">Hello world!</div>

</body>

</html>

 

jQuery Callback Functions

  • JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.
  • To prevent this, you can create a callback function.
  • A callback function is executed after the current effect is 100% finished.

Syntax: 

$(selector).hide(speed,callback);

     Example:

  • The example below has a callback parameter that is a function that will be executed after the hide effect is completed:

$("button").click(function(){
    $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
    });
});

  • The example below has no callback parameter, and the alert box will be displayed before the hide effect is completed:

 

$("button").click(function(){
    $("p").hide(1000);
    alert("The paragraph is now hidden");
});


jQuery - Chaining

With jQuery, you can chain together actions/methods.

  • Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.
  •  It allows us to run multiple jQuery commands, one after the other, on the same element(s).
  • To chain an action, you simply append the action to the previous action.
  • Example: The following example chains together the css(), slideUp(), and slideDown() methods

 

$("#p1").css("color","red")

.slideUp(2000)

.slideDown(2000);


jQuery HTML

jQuery - Get Content and Attributes

jQuery contains powerful methods for changing and manipulating HTML elements and attributes

There are three jQuery methods for DOM manipulation are:

  • text() - Sets or returns the text content of selected elements
  • html() - Sets or returns the content of selected elements (including HTML markup)
  • val() - Sets or returns the value of form fields
  • Example: The following example demonstrates how to get content with the jQuery text() and html() methods:

$("#btn1").click(function(){
    alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
    alert("HTML: " + $("#test").html());
});

The following example demonstrates how to get the value of an input field with the jQuery val() method:

$("#btn1").click(function(){
    alert("Value: " + $("#test").val());
});

Get Attributes - attr()

The jQuery attr() method is used to get attribute values.

The following example demonstrates how to get the value of the href attribute in a link:

<html>

<head>

<script src="/jquery-2.1.4.js"></script>

<script>

$(document).ready(function(){

    $("button").click(function(){

        alert($("#g").attr("href"));

    });

});

</script>

</head>

<body>

<p><a href="http://www.google.com" id="g">Google</a></p>

<button>Show href Value</button>

</body>

</html>

 

 

 

 

jQuery - Set Content and Attributes

We will use the same three methods from the previous page to set content:

  • text() - Sets or returns the text content of selected elements
  • html() - Sets or returns the content of selected elements (including HTML markup)
  • val() - Sets or returns the value of form fields
  • Example: The following example demonstrates how to set content with the jQuery text(), html(), and val() methods:

<html>

<head>

<script src="jquery/2.1.4.js"></script>

<script>

$(document).ready(function(){

    $("#btn1").click(function(){

        $("#test1").text("Hello world!");

    });

    $("#btn2").click(function(){

        $("#test2").html("<b>Hello world!</b>");

    });

    $("#btn3").click(function(){

        $("#test3").val("BHARUCH");

    });

});

</script>

</head>

<body>

<p id="test1">This is a paragraph.</p>

<p id="test2">This is another paragraph.</p>

<p>Input field: <input type="text" id="test3" value="SURAT"></p>

<button id="btn1">Set Text</button>

<button id="btn2">Set HTML</button>

<button id="btn3">Set Value</button>

</body>

</html>

Set Attributes - attr()

  • The jQuery attr() method is also used to set/change single or multiple attribute values.
  • Example: The following example demonstrates how to change (set) the value of the href attribute in a link:

$("button").click(function(){
    $("#g").attr("href", "http://www.google.com");
});

The following example demonstrates how to change (set) the multiple value of the href attribute in a link

$("button").click(function(){
    $("#g").attr({
        "href" : "http://www.google.com",
        "title" : "Google Website"
    });
});


jQuery - Add Elements

Following four jQuery methods are used to add new content:

  • append() - Inserts content at the end of the selected elements
  • prepend() - Inserts content at the beginning of the selected elements
  • after() - Inserts content after the selected elements
  • before() - Inserts content before the selected elements

append() Method

  • Inserts content AT THE END of the selected HTML elements.

<html>

<head>

<script src="jquery2.1.4.js"></script>

<script>

$(document).ready(function(){

    $("#btn1").click(function(){

        $("p").append(" <b>Appended text</b>.");

    });

 

    $("#btn2").click(function(){

        $("ol").append("<li>Appended item</li>");

    });

});

</script>

</head>

<body>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

<ol>

  <li>List item 1</li>

  <li>List item 2</li>

  <li>List item 3</li>

</ol>

<button id="btn1">Append text</button>

<button id="btn2">Append list items</button>

 

</body>

</html>


prepend() Method

  • Inserts content AT THE BEGINNING of the selected HTML elements.

$(document).ready(function(){

    $("#btn1").click(function(){

        $("p").prepend("<b>Prepended text</b>. ");

    });

    $("#btn2").click(function(){

        $("ol").prepend("<li>Prepended item</li>");

    });

});

after() and before() Methods

  • The jQuery after() method inserts content AFTER the selected HTML elements.
  • The jQuery before() method inserts content BEFORE the selected HTML elements.

<html>

<head>

<script src="jquery-2.1.4.js"></script>

<script>

$(document).ready(function(){

    $("#btn1").click(function(){

        $("img").before("<b>Before</b>");

    });

 

    $("#btn2").click(function(){

        $("img").after("<i>After</i>");

    });

});

</script>

</head>

<body>

 

<img src="Bluehills.jpeg" width="100" height="140"><br><br>

 

<button id="btn1">Insert before</button>

<button id="btn2">Insert after</button>

 

</body>

</html>

 


jQuery - Remove Elements

  • To remove elements and content, there are mainly two jQuery methods:
    • remove() - Removes the selected element (and its child elements)
    • empty() - Removes the child elements from the selected element

 

remove() Method

  • The jQuery remove() method removes the selected element(s) and its child elements.

<html>

<head>

<script src="jquery-2.1.4.js"></script>

<script>

$(document).ready(function(){

    $("button").click(function(){

        $("#div1").remove();

    });

});

</script>

</head>

<body>

<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">

This is some text in the div.

<p>This is a paragraph in the div.</p>

<p>This is another paragraph in the div.</p>

</div>

<br>

<button>Remove div element</button>

</body>

</html>

empty() Method

  • The jQuery empty() method removes the child elements of the selected element(s).

$(document).ready(function(){

    $("button").click(function(){

        $("#div1").empty();

    });

});

 

 

 

 


jQuery Manipulating CSS

jQuery has several methods for CSS manipulation. We will look at the following methods:

  • addClass() - Adds one or more classes to the selected elements
  • removeClass() - Removes one or more classes from the selected elements
  • toggleClass() - Toggles between adding/removing classes from the selected elements
  • css() - Sets or returns the style attribute
  • Let us consider following style sheet example:

.important {
    
font-weight: bold;
    
font-size: xx-large;
}

.blue {
    
color: blue;
}

jQuery addClass() Method

The following example shows how to add class attributes to different elements. Of course you can select multiple elements, when adding classes:

$("button").click(function(){
    $("h1, h2, p").addClass("blue");
    $("div").addClass("important");
});

You can also specify multiple classes within the addClass() method:

 

$("button").click(function(){
    $("#div1").addClass("important blue");
});

 

jQuery removeClass() Method

The following example shows how to remove a specific class attribute from different elements:

$("button").click(function(){
    $("h1, h2, p").removeClass("blue");
});

 

jQuery toggleClass() Method

The following example will show how to use the jQuery toggleClass() method. This method toggles between adding/removing classes from the selected elements:

$("button").click(function(){
    $("h1, h2, p").toggleClass("blue");
});

 

jQuery css() Method

The css() method sets or returns one or more style properties for the selected elements.

Return a CSS Property

To return the value of a specified CSS property, use the following syntax:

css("propertyname");

 

The following example will return the background-color value of the FIRST matched element:

$(document).ready(function(){

    $("button").click(function(){

        alert("Background color = " + ("p").css("background-color"));

    });

});

Set a CSS Property

To set a specified CSS property, use the following syntax:

 

css("propertyname","value");

The following example will set the background-color value for ALL matched elements:

$(document).ready(function(){

    $("button").click(function(){

        $("p").css("background-color", "yellow");

    });

});

 

 

Set Multiple CSS Properties

To set multiple CSS properties, use the following syntax:

css({"propertyname":"value","propertyname":"value",...});

 

The following example will set a background-color and a font-size for ALL matched elements:

 

    $("p").css({"background-color": "yellow", "font-size": "200%"});

 


jQuery Dimension Methods

jQuery has several important methods for working with dimensions:

  • width()
  • height()
  • innerWidth()
  • innerHeight()
  • outerWidth()
  • outerHeight()

 

jQuery Dimensions

 

jQuery width() and height() Methods

  • The width() method sets or returns the width of an element (excludes padding, border and margin).
  • The height() method sets or returns the height of an element (excludes padding, border and margin).
  • The following example returns the width and height of a specified <div> element:

<html>

<head>

<script src=" jquery-2.1.4.js"></script>

<script>

$("document").ready(function(){

    $("button").click(function(){

        var txt = "";

        txt += "Width of div: " + $("#div1").width() + "</br>";

        txt += "Height of div: " + $("#div1").height();

        $("#div1").html(txt);

    });

});

</script>

<style>

#div1 {

    height: 100px;

    width: 300px;

    padding: 10px;

    margin: 3px;

    border: 1px solid blue;

    background-color: lightblue;

}

</style>

</head>

<body>

 

<div id="div1"></div>

<br>

 

<button>Display dimensions of div</button>

 

<p>width() - returns the width of an element.</p>

<p>height() - returns the height of an element.</p>

 

</body>

</html>

 

jQuery innerWidth() and innerHeight() Methods

·       The innerWidth() method returns the width of an element (includes padding).

·       The innerHeight() method returns the height of an element (includes padding).

jQuery outerWidth() and outerHeight() Methods

  • The outerWidth() method returns the width of an element (includes padding and border).
  • The outerHeight() method returns the height of an element (includes padding and border).

The following example sets the width and height of a specified <div> element:

$("button").click(function(){
    $("#div1").width(500).height(500);
});

 

jQuery Traversing

What is Traversing?

jQuery traversing, which means "move through", are used to "find" (or select) HTML elements based on their relation to other elements. Start with one selection and move through that selection until you reach the elements you desire.

The image below illustrates a family tree. With jQuery traversing, you can easily move up (ancestors), down (descendants) and sideways (siblings) in the family tree, starting from the selected (current) element. This movement is called traversing - or moving through - the DOM.

jQuery Dimensions

 

Illustration explained:

  • The <div> element is the parent of <ul>, and an ancestor of everything inside of it
  • The <ul> element is the parent of both <li> elements, and a child of <div>
  • The left <li> element is the parent of <span>, child of <ul> and adescendant of <div>
  • The <span> element is a child of the left <li> and a descendant of <ul> and <div>
  • The two <li> elements are siblings (they share the same parent)
  • The right <li> element is the parent of <b>, child of <ul> and adescendant of <div>
  • The <b> element is a child of the right <li> and a descendant of <ul> and <div>

Traversing the DOM

  • jQuery provides a variety of methods that allows us to traverse the DOM.
  • The largest category of traversal methods are tree-traversal.

jQuery Traversing - Ancestors

  • An ancestor is a parent, grandparent, great-grandparent, and so on.
  • With jQuery you can traverse up the DOM tree to find ancestors of an element.

Traversing Up the DOM Tree

Three useful jQuery methods for traversing up the DOM tree are:

  • parent()
  • parents()
  • parentsUntil()

jQuery parent() Method

  • The parent() method returns the direct parent element of the selected element.
  • This method only traverse a single level up the DOM tree.
  • The following example returns the direct parent element of each <span> elements:

<html>

<head>

<style>

.ancestors * {

    display: block;

    border: 2px solid lightgrey;

    color: lightgrey;

    padding: 5px;

    margin: 15px;

}

</style>

<script src="jquery-2.1.4.js"></script>

<script>

$(document).ready(function(){

    $("span").parent().css({"color": "red", "border": "2px solid red"});

});

</script>

</head>

<body>

 

<div class="ancestors">

  <div style="width:500px;">div (great-grandparent)

    <ul>ul (grandparent) 

      <li>li (direct parent)

        <span>span</span>

      </li>

    </ul>  

  </div>

 

  <div style="width:500px;">div (grandparent)  

    <p>p (direct parent)

        <span>span</span>

      </p>

  </div>

</div>

 

</body>

</html>

 

jQuery parents() Method

  • The parents() method returns all ancestor elements of the selected element, all the way up to the document's root element (<html>).
  • The following example returns all ancestors of all <span> elements:

<html>

<head>

<style>

.ancestors * {

    display: block;

    border: 2px solid lightgrey;

    color: lightgrey;

    padding: 5px;

    margin: 15px;

}

</style>

<script src="jquery-2.1.4.js"></script>

 

<script>

$("document").ready(function(){

    $("span").parents().css({"color": "red", "border": "2px solid red"});

});

</script>

<body class="ancestors">body (great-great-grandparent)

  <div style="width:500px;">div (great-grandparent)

    <ul>ul (grandparent) 

      <li>li (direct parent)

        <span>span</span>

      </li>

    </ul>  

  </div>

</body>

 

  • You can also use an optional parameter to filter the search for ancestors.
  • The following example returns all ancestors of all <span> elements that are <ul> elements:

<script>

$(document).ready(function(){

    $("span").parents("ul").css({"color": "red", "border": "2px solid red"});

});

</script>

 

jQuery parentsUntil() Method

  • The parentsUntil() method returns all ancestor elements between two given arguments.
  • The following example returns all ancestor elements between a <span> and a <div> element:

<script>

$(document).ready(function(){

    $("span").parentsUntil("div").css({"color": "red", "border": "2px solid red"});

});

</script>

 


jQuery Traversing - Descendants

·       A descendant is a child, grandchild, great-grandchild, and so on.

·       With jQuery you can traverse down the DOM tree to find descendants of an element.

Traversing Down the DOM Tree

·       Two useful jQuery methods for traversing down the DOM tree are:

·        children()

·        find()

 

jQuery children() Method

·       The children() method returns all direct children of the selected element.

·       This method only traverse a single level down the DOM tree.

·       The following example returns all elements that are direct children of each <div> elements:

<html>

<head>

<style>

.descendants * {

    display: block;

    border: 2px solid lightgrey;

    color: lightgrey;

    padding: 5px;

    margin: 15px;

}

</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<script>

$("document").ready(function(){

    $("div").children().css({"color": "red", "border": "2px solid red"});

});

</script>

</head>

<body>

 

<div class="descendants" style="width:500px;">div (current element)

  <p>p (child)

    <span>span (grandchild)</span>    

  </p>

  <p>p (child)

    <span>span (grandchild)</span>

  </p>

</div>

 

</body>

</html>

 

jQuery find() Method

The find() method returns descendant elements of the selected element, all the way down to the last descendant.

<html>

<head>

<style>

.descendants * {

    display: block;

    border: 2px solid lightgrey;

    color: lightgrey;

    padding: 5px;

    margin: 15px;

}

</style>

<script src="jquery-2.1.4.js"></script>

<script>

$("document").ready(function(){

    $("div").find("span").css({"color": "red", "border": "2px solid red"});

});

</script>

</head>

<body>

 

<div class="descendants" style="width:500px;">div (current element)

  <p>p (child)

    <span>span (grandchild)</span>    

  </p>

  <p>p (child)

    <span>span (grandchild)</span>

  </p>

</div>

 

</body>

</html>


jQuery Traversing - Siblings

  • Siblings share the same parent.
  • With jQuery you can traverse sideways in the DOM tree to find siblings of an element.
  • There are many useful jQuery methods for traversing sideways in the DOM tree:

·        siblings()

·        next()

·        nextAll()

·        nextUntil()

·        prev()

·        prevAll()

·        prevUntil()

jQuery siblings() Method

  • The siblings() method returns all sibling elements of the selected element.
  • The following example returns all sibling elements of <h2>:

<html>

<head>

<style>

.siblings * {

    display: block;

    border: 2px solid lightgrey;

    color: lightgrey;

    padding: 5px;

    margin: 15px;

}

</style>

<script src=" jquery-2.1.4.js"></script>

<script>

$("document").ready(function(){

    $("h2").siblings().css({"color": "red", "border": "2px solid red"});

});

</script>

</head>

<body class="siblings">

<div>div (parent)

  <p>p</p>

  <span>span</span>

  <h2>h2</h2>

  <h3>h3</h3>

  <p>p</p>

</div></body></html>

 

 

jQuery next() Method

The next() method returns the next sibling element of the selected element.

jQuery nextAll() Method

The nextAll() method returns all next sibling elements of the selected element.

jQuery nextUntil() Method

The nextUntil() method returns all next sibling elements between two given arguments.

jQuery prev(), prevAll() & prevUntil() Methods

The prev(), prevAll() and prevUntil() methods work just like the methods above but with reverse functionality: they return previous sibling elements (traverse backwards along sibling elements in the DOM tree, instead of forward).


jQuery Traversing - Filtering

Narrow Down The Search For Elements

The three most basic filtering methods are first(), last() and eq(), which allow you to select a specific element based on its position in a group of elements.

Other filtering methods, like filter() and not() allow you to select elements that match, or do not match, a certain criteria.

jQuery first() Method

The first() method returns the first element of the selected elements.

The following example selects the first <p> element inside the first <div> element:

<html>

<head>

<script src=" jquery-2.1.4.js"></script>

<script>

$("document").ready(function(){

    $("div p").first().css("background-color", "yellow");

});

</script>

</head>

<body>

 

<h1>Welcome to My Homepage</h1>

 

<p>This is the first paragraph in body.</p>

 

<div style="border: 1px solid black;">

  <p>This is the first paragraph in a div.</p>

  <p>This is the last paragraph in a div.</p>

</div><br>

 

<div style="border: 1px solid black;">

  <p>This is the first paragraph in another div.</p>

  <p>This is the last paragraph in another div.</p>

</div>

 

<p>This is the last paragraph in body.</p>

 

</body>

</html>

jQuery last() Method

The last() method returns the last element of the selected elements.

jQuery eq() method

The eq() method returns an element with a specific index number of the selected elements.

The index numbers start at 0, so the first element will have the index number 0 and not 1

 

<html>

<head>

<script src="jquery-2.1.4.js"></script>

<script>

$("document").ready(function(){

    $("p").eq(1).css("background-color", "yellow");

});

</script>

</head>

<body>

 

<h1>Welcome to My Homepage</h1>

 

<p>My name is Donald (index 0).</p>

<p>Donald Duck (index 1).</p>

<p>I live in Duckburg (index 2).</p>

<p>My best friend is Mickey (index 3).</p>

 

</body>

</html>

jQuery filter() Method

The filter() method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.

<html>

<head>

<script src="jquery-2.1.4.js"></script>

<script>

$("document").ready(function(){

    $("p").filter(".intro").css("background-color", "yellow");

});

</script>

</head>

<body>

 

<h1>Welcome to My Homepage</h1>

 

<p>My name is Donald.</p>

<p class="intro">I live in Duckburg.</p>

<p class="intro">I love Duckburg.</p>

<p>My best friend is Mickey.</p>

 

</body>

</html>

jQuery not() Method

The not() method returns all elements that do not match the criteria.

 

Post a Comment

If you have any doubts, Please let me know
Thanks!

Previous Post Next Post