Selectors and DOM

jQuery selectors are based on CSS selectors with additional pseudo-selectors. Mastering selectors is key to efficient jQuery code.

CSS Selectors

JavaScript
// Element selectors
$('p')                       // All paragraphs
$('h1, h2, h3')             // All headings
$('div.container')           // div with class container
$('#main-content')           // Element with id main-content
$('ul > li')                 // Direct children
$('a[href^="https"]')       // Links starting with https
$('a[href$=".pdf"]')        // Links ending with .pdf
$('input[type="text"]')     // Text inputs
$('a[href*="example"]')     // Links containing "example"

jQuery Pseudo-Selectors

JavaScript
// Visible/hidden
$('div:visible')             // Visible elements
$('div:hidden')              // Hidden elements

// Position
$('li:first')               // First li
$('li:last')                // Last li
$('li:eq(2)')               // Third li (0-indexed)
$('li:odd')                 // Odd-indexed (1, 3, 5...)
$('li:even')                // Even-indexed (0, 2, 4...)

// Content
$('p:contains("Hello")')    // Paragraphs containing "Hello"
$('div:has(p)')             // Divs that contain a <p>
$('td:empty')               // Empty table cells
$('input:empty')            // Empty inputs

// Form selectors
$('input:first-child')       // Inputs that are first child
$('input:enabled')           // Enabled inputs
$('input:disabled')          // Disabled inputs
$('input:checked')           // Checked checkboxes/radios
$('input:selected')          // Selected options
$('input:required')          // Required inputs
$('input:invalid')           // Invalid inputs

DOM Manipulation Methods

Creating Elements

JavaScript
// Create new elements
var $newItem = $('<li class="item">New Item</li>');
var $newDiv = $('<div>').addClass('card').text('Hello');

// Append to DOM
$('ul').append($newItem);         // Add to end of ul
$('ul').prepend($newItem);        // Add to beginning
$newItem.appendTo($('ul'));       // Same as append, reversed
$newItem.insertAfter($('ul li:last'));  // Insert after specific element

Removing Elements

JavaScript
$('li').remove();                 // Remove from DOM completely
$('li').detach();                 // Remove but keep jQuery data
$('li').empty();                  // Remove children (keep element)
$('ul').html('');                 // Same as empty()

Replacing and Cloning

JavaScript
$('p').replaceWith('<h2>New Heading</h2>');  // Replace all <p>
$('li').clone().appendTo('ul');              // Clone and append
$('li').clone(true).appendTo('ul');          // Clone with event handlers

Dimensions and Position

JavaScript
var $el = $('.box');

// Dimensions
$el.width();              // Content width (no padding/border)
$el.height();             // Content height
$el.innerWidth();         // Content + padding
$el.innerHeight();        // Content + padding
$el.outerWidth();         // Content + padding + border
$el.outerWidth(true);     // Content + padding + border + margin

// Position (relative to offset parent)
var pos = $el.position();
console.log(pos.top, pos.left);

// Offset (relative to document)
var offset = $el.offset();
console.log(offset.top, offset.left);

Practical Examples

Dynamic List Builder

JavaScript
// Add item on button click
$('#add-btn').on('click', function() {
    var text = $('#item-input').val().trim();
    if (text) {
        $('<li>')
            .html(text + ' <button class="delete">✕</button>')
            .hide()
            .appendTo('#item-list')
            .fadeIn(300);
        $('#item-input').val('').focus();
    }
});

// Delete item
$('#item-list').on('click', '.delete', function() {
    $(this).parent('li').fadeOut(200, function() {
        $(this).remove();
    });
});

Form Data Collection

JavaScript
$('form').on('submit', function(e) {
    e.preventDefault();
    
    var formData = {};
    $(this).find('input, select, textarea').each(function() {
        var name = $(this).attr('name');
        var value = $(this).val();
        if (name) formData[name] = value;
    });
    
    console.log('Form data:', formData);
});

💡 Tip: Use .on() for event delegation instead of direct binding — it handles dynamically added elements automatically.

Next: Events