DOM Element Selection and Manipulation
jQuery provides powerful methods for selecting and manipulating DOM elements. Understanding these fundamental operations is essential for creating dynamic web interfaces.
Element Selection Methods
jQuery offers multiple approaches to select DOM elements using CSS-style selectors:
$(function() {
// Select by ID
var contentContainer = $('#content');
// Select by class
var spanElements = $('.span-class');
// Select by tag name
var listItems = $('li');
// Select by attribute
var noFollowLinks = $('a[rel="nofollow"]');
});
Finding Child Elements
When the exact location of elements is unknown, jQuery's find() method can traverse the DOM:
$(function() {
// Direct child selection
var leftPanel = $('#content .top .top-left');
// Using find() method
var anchorElement = $('.parent').find('a');
});
Creating and Inserting Elements
jQuery enables dynamic element creation and insertion:
$(function() {
// Create elements after existing ones
$('#itemList').after("<button>Action Button</button>");
$('<button>Secondary Action</button>').insertAfter("#itemList");
// Add elements to lists
$('#itemList').append("<li>New List Item</li>");
});
Modifying Element Content
Content manipulation includes replacing, prepending, and appending:
$(function() {
// Replace content
$('#container').html("<p>Updated content</p>");
// Add content at beginning
$('#container').prepend("<p>Prepended content</p>");
// Add content at end
$('#container').append("<button>Action Button</button>");
// Set input values
$('#textInput').val("Default text value");
});
Attribute and Property Modification
Element properties and attributes can be dynamically changed:
$(function() {
// Modify checkbox state
$('input[type="checkbox"]').prop('checked', true);
// Disable inputs
$('input[type="text"]').prop('disabled', true);
// Change input values
$('input[type="text"]').val("New input value");
});
CSS Class Manipulation
Dynamic styling through class addition and removal:
$(function() {
$('#styleText').click(function() {
// Remove existing classes
$('#textElement').removeClass();
// Add new class
$('#textElement').addClass('highlighted');
});
});
Form Element Control
Enabling and disabling form elements based on user input:
$(function() {
$('#searchField').keyup(function() {
if ($(this).val().length > 2) {
$('#searchButton').prop("disabled", false);
} else {
$('#searchButton').prop("disabled", true);
}
});
});
Dynamic Image Updates
Image sources can be changed dynamically while preventing browser caching:
$(function() {
$('#colorButton').click(function() {
$('#colorBox').prop("src", "images/blue.png?t=" + new Date().getTime());
});
});
Populating List Elements
Dynamically filling lists from JavaScript arrays:
$(function() {
var userData = [
{id: 1, firstName: 'John', lastName: 'Smith'},
{id: 2, firstName: 'Jane', lastName: 'Doe'}
];
$.each(userData, function(index, user) {
$('#userList').append("<li>#" + user.id + " " + user.firstName + " " + user.lastName + "</li>");
});
});
Implementing Pagination
Creating paginated data displays with navigation controls:
$(function() {
var pageSize = 4;
var currentPage = 1;
var totalItems = itemArray.length;
function updateDisplay() {
var endIndex = currentPage * pageSize;
var startIndex = endIndex - pageSize;
var pageItems = itemArray.slice(startIndex, endIndex);
$('#itemList').empty();
// Navigation control logic
$('.prevButton').prop("disabled", currentPage <= 1);
$('.nextButton').prop("disabled", (currentPage * pageSize) >= totalItems);
// Populate current page
$.each(pageItems, function(index, item) {
$('#itemList').append("<li><strong>" + item.name + "</strong> (" + item.category + ")</li>");
});
}
});
Element Removal and Reuse
Removing elements and cloning templates for reuse:
$(function() {
// Remove elements
$('.deleteButton').click(function() {
$(this).parent().remove();
});
// Reuse element templates
$.each(dataItems, function(index, item) {
var itemTemplate = $('#itemList li').first().clone();
itemTemplate.find('.itemName').html(item.name);
itemTemplate.find('.itemType').html(item.type);
itemTemplate.removeClass();
itemTemplate.addClass(item.styleClass);
$('#itemList').append(itemTemplate);
});
});
Event Handling and User Interaction
Button Click Detection
Multiple methods for detecting button interactions:
$(function() {
// Direct click binding
$('.actionButton').click(function() {
alert("Button clicked");
});
// Event delegation
$('body').on("click", ".dynamicButton", function() {
alert("Dynamic button clicked");
});
});
Element Click Detection
Attaching click handlers to various element types:
$(function() {
$('a').click(function() {
alert("Link clicked");
});
$('body').on('click', 'input[type="text"]', function() {
alert("Text input clicked");
});
$('.clickableDiv').click(function() {
alert("Div element clicked");
});
});
Chenge Event Detection
Monitoring value changes in form elements:
$(function() {
$('#selectionList').change(function() {
var selectedValue = $(this).val();
alert("Selection changed to: " + selectedValue);
});
$('#textInput').change(function() {
var inputValue = $(this).val();
alert("Input changed to: " + inputValue);
});
});
Content Updates Based on User Input
Dynamical updating content in response to user actions:
$(function() {
$('#titleSelector').change(function() {
var titleText = "";
switch ($(this).val()) {
case "1":
titleText = "First title content";
break;
case "2":
titleText = "Second title content";
break;
case "3":
titleText = "Third title content";
break;
default:
titleText = "Default title";
}
$('#mainHeading').html(titleText);
});
});
Keyboard Event Handling
Detecting and responding to keyboard interactions:
$(function() {
$('.textInput').keyup(function() {
$('#eventLog').append("<li>Key released</li>");
});
$('.textInput').keydown(function(event) {
$('#eventLog').append("<li>Key pressed</li>");
if (event.which == 13) {
$('#eventLog').append("<li>Enter key detected</li>");
}
});
});
Input Character Restrictions
Limiting acceptable input characters using regular expressions:
$(function() {
$('.restrictedInput').keypress(function(event) {
var pattern = new RegExp("^[a-zA-Z0-9]+$");
var character = String.fromCharCode(event.which);
if (!pattern.test(character)) {
return false;
}
});
});
Mouse Hover Effects
Creating interactive hover-based user experiences:
$(function() {
$('.infoElement').mouseover(function() {
$('.infoDisplay').html($(this).attr("data-info"));
$('.infoDisplay').fadeIn();
}).mouseleave(function() {
$('.infoDisplay').hide();
});
});
Manual Event Triggering
Programmatical triggering events from code:
$(function() {
$('.submitButton').on("click", function() {
alert("Form submission initiated");
});
$('input[type="text"]').keypress(function(event) {
if (event.which == 13) {
$('.submitButton').trigger("click");
}
});
});
Event Prevention
Stopping default browser behaviors and event propagation:
$(function() {
$('.submitButton').on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var confirmation = confirm("Confirm form submission?");
if (confirmation) {
$('#dataForm').submit();
}
});
});
Custom Event Creation
Defining and triggering custom application-specific events:
$(function() {
$('.displayArea').on("updateDisplay", function(event, color, message) {
$(this).html(message);
$(this).css("color", color);
});
$("button").click(function() {
var buttonColor = $(this).attr("data-color");
$('.displayArea').trigger("updateDisplay", [buttonColor, buttonColor + ' action activated']);
});
});