jQueryIntermediateFree to read

jQuery: selectors, effects, traversal and AJAX

DOM manipulation the jQuery way — selecting and changing elements, the effect methods, walking the DOM tree, event delegation and AJAX calls.

What you will be able to do
  • Select and change elements with jQuery and know the plain-DOM equivalent.
  • Use the effect methods with the right duration and callback.
  • Delegate events so they keep working on elements added later.

Why jQuery?

jQuery simplifies HTML document traversing, event handling, and Ajax interactions.

CDN Link

https://code.jquery.com/jquery-3.6.0.min.js

Write less, do more

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

Powerful Selectors

jQuery selectors allow you to select and manipulate HTML elements.

Basic Selectors

SelectorExampleWhat it selects
Element$("p")Selects all <p> elements
ID$("#demo")Selects element with id='demo'
Class$(".test")Selects elements with class='test'

Attribute Selectors

SelectorExampleWhat it selects
Attribute$("[href]")Selects elements with href attribute
Attribute Value$("[href='default.htm']")Selects elements with exact href value
Attribute Contains$("[href*='fueint']")Selects elements with href containing 'fueint'

Hierarchy Selectors

SelectorExampleWhat it selects
Descendant$("div p")Selects all <p> inside <div>
Child$("div > p")Selects <p> directly inside <div>
Sibling$("div + p")Selects <p> immediately after <div>

Interactive Events

jQuery provides elegant methods for handling user interactions with clean, intuitive syntax.

1. Mouse Events

EventSyntax
click$(selector).click(function)
dblclick$(selector).dblclick(function)
hover$(selector).hover(inFunction, outFunction)
mousedown$(selector).mousedown(function)
mouseup$(selector).mouseup(function)

2. Keyboard Events

EventSyntax
keypress$(selector).keypress(function)
keydown$(selector).keydown(function)
keyup$(selector).keyup(function)

3. Form Events

EventSyntax
submit$(selector).submit(function)
change$(selector).change(function)
focus$(selector).focus(function)
blur$(selector).blur(function)
select$(selector).select(function)

4. Document Events

EventSyntax
ready$(document).ready(function)
load$(window).load(function)
unload$(window).unload(function)
resize$(window).resize(function)
scroll$(window).scroll(function)
Pro Tip: Event Delegation

For dynamic elements, use $(document).on('click', '.selector', function) instead of direct binding. This ensures events work for elements added after page load.

jQuery Effects

Create smooth animations and transitions with jQuery effect methods.

Display Effects

  • .hide()
  • .show()
  • .toggle()

Slide Effects

  • .slideDown()
  • .slideUp()
  • .slideToggle()

Fade Effects

  • .fadeIn()
  • .fadeOut()
  • .fadeTo()
  • .fadeToggle()

Other Effects

  • .animate()
  • .delay()

Effect Syntax

$(selector).show([speed, callback]);

Speed Parameters

  • Words: slow, "normal", "fast"
  • Milliseconds: 1000 (1 second)

Callback Function

Executes after animation completes. Called once per animated element.

Example Usage

// Fade out with callback
$("#box").fadeOut("slow", function() {
console.log("Animation complete");
});
// Slide toggle with speed
$(".panel").slideToggle(500);
// Custom animate
$(".item").animate({
left: "250px",
opacity: "0.5"
}, 1000);
Try these effects:
  • fadeOut() - Gradually hides elements
  • slideToggle() - Toggles slide up/down
  • animate() - Create custom animations

jQuery HTML Methods

Manipulate HTML content and attributes with jQuery powerful methods.

Syntax

Return content:
$(selector).html()
Set content:
$(selector).html(content)
Set with function:
$(selector).html(function(index, currentContent))

Parameters

content

  • What it is: The new content to set
  • What it can be: Text or HTML (can include tags)

function(index, currentContent)

  • index: Position of element (0, 1, 2...)
  • currentContent: The elements current HTML

Example

<!DOCTYPE html>
<html>
<head>
<title>jQuery html() Method</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
    <body style={{ textAlign: "center" }}>
    <h1 style={{ color: "green" }}>Hello World</h1>
    <h2>Hello Teens</h2>
    <button>Click</button>
    <script>
    $(document).ready(function() {
    $("button").click(function() {
    alert($("h2").html());
    });
    });
    </script>
</body>
</html>
Code Explanation:
  • When button is clicked, shows alert with HTML content of <h2>
  • Demonstrates reading content with .html()
  • Document ready ensures DOM is loaded first

Practical Usage

Setting HTML Content

// Set simple text
  $("#title").html("New Heading");
  // Set HTML content
  $("#container").html("<div class='alert'>Success!</div>");

  // Using function
  $("li").html(function(index) {
  return "Item " + (index + 1);
});

Getting HTML Content

// Get content
  var content = $("#article").html();
  // Use in condition
  if ($("#warning").html() === "") {
  $("#warning").html("<strong>Alert!</strong>");
  }
  // Log all paragraph content
  $("p").each(function() {
  console.log($(this).html());
});

jQuery DOM Traversing

Navigate and manipulate elements based on their relationships in the DOM tree.

DOM Tree Structure

DOM tree structure
<div>
  <ul>
    <li>
      <span>
    <li>
      <b>

Relationship Types

RelationshipWhat it meansjQuery
ParentDirect container element$('ul').parent()
ChildDirect contained element$('div').children()
SiblingElements at same level$('li').siblings()
AncestorAny element above in hierarchy$('span').parents()
DescendantAny element below in hierarchy$('div').find('span')

Practical Examples

Navigation Menu

// Highlight parent menu item
  $(".menu-item.active").parent()
   .addClass("bg-[#B45309] text-white");

// Find all child links
   $(".nav-bar").find("a")
    .addClass("hover:text-[#B45309]");

Form Validation

// Find closest form
  $(".error-message").closest("form")
     .addClass("error-state");

 // Get sibling inputs
  $(".invalid").siblings("input")
      .addClass("border-red-500");

Traversal Methods

Moving Down

MethodWhat it does
.children()Direct child elements
.find()All matching descendants

Moving Up

MethodWhat it does
.parent()Immediate parent element
.parents()All ancestor elements
.closest()First matching ancestor

Moving Sideways

MethodWhat it does
.siblings()All sibling elements
.next()Immediate next sibling
.prev()Immediate previous sibling
.filter()Reduce matched elements
.first()/.last()First/last element in set

Practical Examples in full

Navigation Example

// Highlight parent of active link
$(".active").parent().addClass("highlight");

// Find all links in navigation
$("#nav").find("a").addClass("text-blue-500");

// Get next sibling of current tab
$(".tab.active").next().show();

Form Example

// Find closest form ancestor
$("input").closest("form").addClass("needs-validation");

// Get all siblings of error message
$(".error").siblings().addClass("border-red-500");

// Filter visible inputs
$("input").filter(":visible").val("");

jQuery AJAX & Misc Methods

Powerful tools for asynchronous requests and utility functions.

AJAX Methods

AJAX Fundamentals

The jQuery ajax() method lets you send and receive data between a web browser and server asynchronously.

Syntax:
$.ajax({name:value, name:value, ...})

Common Parameters:

  • type
  • url
  • data
  • dataType
  • success
  • error
  • cache
  • async

JSON Handling

jQuery provides built-in support for handling JSON data in AJAX requests.

// Example: Fetching JSON data
$.ajax({
  url: 'https://api.example.com/users',
    method: 'GET',
    dataType: 'json',
    success: function(users) {
        users.forEach(function(user) {
        console.log(user.name);
         });
       },
    error: function(xhr, status, error) {
    console.error(error);
        }
});

Miscellaneous Methods

.each()

Iterates over jQuery objects/arrays

$("li").each(function(index, element) {
  console.log("Item " + (index + 1) + ": "
   + $(element).text());
});

.data()

Stores/retrieves arbitrary data

$("#myDiv").data("userInfo",
{ name: "Alice", age: 30 });

// Retrieve
$("#myDiv").data("userInfo").name;

.noConflict()

Avoids $ variable conflicts

var jQ = jQuery.noConflict();
jQ("p").text("Updated using jQ");

.param()

Creates query strings

var data = { name: "Bob", city: "New York"
};
var queryString = jQuery.param(data);
// "name=Bob&city=New%20York"

.index()

Finds element position

var listItem = $("#item3");
var index = $("li").index(listItem);
// Returns position (0-based)

Quick Reference

MethodWhat it does
.each()Loop through elements
.data()Get/set element data
.get()Get DOM elements as array
.index()Find element position
.toArray()Convert to JavaScript array
.removeData()Remove stored data

Object-Oriented Programming (OOPs)

Organizing code into objects containing data and behavior.

Core Concepts

ConceptWhat it isExample
ClassBlueprint for creating objectsclass Vehicle {...}
ObjectInstance of a classconst tesla = new Vehicle()
EncapsulationBundling data & methodsprivate #mileage
InheritanceChild class extends parentclass Car extends Vehicle
PolymorphismSame method, different behaviorparent.honk() vs child.honk()
AbstractionHiding complex logicSimple public interfaces

OOPs in Action

// 1. CLASS (Blueprint)
class Vehicle {
// Private field (Encapsulation)
#mileage;

constructor(make, model) {
this.make = make;
this.model = model;
this.#mileage = 0;
}

// Public method (Abstraction)
start() {
console.log(`${this.make} ${this.model} started`);
}

// Encapsulation: Controlled access
getMileage() {
return this.#mileage;
}

// Polymorphism (default)
honk() {
console.log("Beep beep!");
}
}

// 2. INHERITANCE
 class ElectricCar extends Vehicle {
   constructor(make, model, battery) {
      super(make, model);
         this.battery = battery;
   }

// 3. POLYMORPHISM
    honk() {
        console.log("Silent electric beep!");
    }

    charge() {
          console.log(`${this.make} charging...`);
             }
    }

// 4. OBJECT (Instance)
const tesla = new ElectricCar("Tesla", "Model 3", "100kWh");

// Usage:
tesla.start();       // Inherited
tesla.honk();        // Polymorphism
tesla.charge();      // Child method
tesla.getMileage();  // Encapsulated access
Key Concepts Demonstrated:
  • Class → Vehicle is the blueprint
  • Object → tesla is the concrete instance
  • Encapsulation → #mileage is private
  • Inheritance → ElectricCar extends Vehicle
  • Polymorphism → Different honk() behaviors
  • Abstraction → Simple public interfaces

Output When Executed:

Tesla Model 3 started
Silent electric beep!
Tesla charging...
0

Why Use OOPs?

  • Modular code organization
  • Easier maintenance and updates
  • Code reusability through inheritance
  • Data protection via encapsulation
  • Flexibility through polymorphism
  • Reduced complexity via abstraction
CoachingjQuery

Master JavaScript — basics to advanced

From variables to async work and the DOM, with projects you keep and can show.

Learn it here. Build it with us when you are ready.

Every lesson on this site is free and stays free. Bring the script that only works the first time and a mentor will find out why.

WhatsAppMessage us on WhatsApp
Visit12, Sri Vigneshwara Nagar, Amman Kovil
Saravanampatti, Coimbatore, TN, India — 641035

தெய்வத்தான் ஆகா தெனினும் முயற்சிதன்மெய்வருத்தக் கூலி தரும்.