DOM Manipulation & Events
jQuery: DOM Manipulation & Events jQuery is a fast, lightweight JavaScript library that simplifies DOM traversal, event handling, animation, and AJAX. Despite t…
jQuery: DOM Manipulation & Events
jQuery is a fast, lightweight JavaScript library that simplifies DOM traversal, event handling, animation, and AJAX. Despite the rise of vanilla JS and modern frameworks, jQuery runs on a vast majority of websites and remains important in legacy codebases.
Setup & Selectors
<!-- CDN include -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<!-- Document ready -->
<script>
$(document).ready(function() {
// DOM is ready — safe to manipulate
});
// Shorthand
$(function() {
// same as document ready
});
</script>// CSS-style selectors
$('#myId') // by ID
$('.myClass') // by class
$('p') // by tag
$('ul li') // descendant
$('ul > li') // direct child
$('input[type="text"]') // attribute
$('.parent .child') // nested
// jQuery-specific selectors
$(':first') // first matched
$(':last') // last matched
$(':even'), $(':odd') // 0-indexed
$(':not(.active)') // negation
$(':contains("text")') // elements with text
$(':visible'), $(':hidden')
$(':checked'), $(':disabled'), $(':enabled')
$(':input') // all form elements
$('tr:nth-child(2n)') // every other row
// Finding relative elements
$('#parent').find('.child') // descendants
$('.item').closest('.list') // nearest ancestor
$('.item').siblings() // siblings
$('.item').next() // next sibling
$('.item').prev() // previous sibling
$('.item').parent() // direct parent
$('.item').parents('ul') // all ancestor ul elements
$('.item:first').nextAll() // all following siblingsDOM Manipulation
// Content
$('#title').text() // get text content
$('#title').text('New Title') // set text content
$('#box').html() // get inner HTML
$('#box').html('<b>Bold</b>') // set inner HTML (use carefully — XSS risk)
$('input').val() // get input value
$('input').val('new value') // set input value
// Attributes & Properties
$('img').attr('src') // get attribute
$('img').attr('src', '/new.jpg') // set attribute
$('img').attr({ src: '/img.jpg', alt: 'Photo' }) // set multiple
$('img').removeAttr('alt')
$(':checkbox').prop('checked') // checked property
$(':checkbox').prop('checked', true) // set property
// CSS
$('.box').css('color') // get
$('.box').css('color', 'red') // set
$('.box').css({ color: 'red', fontSize: '16px' }) // multiple
// Classes
$('.item').addClass('active')
$('.item').removeClass('active')
$('.item').toggleClass('active')
$('.item').hasClass('active') // returns boolean
// DOM insertion
$('#list').append('<li>Last item</li>') // inside, at end
$('#list').prepend('<li>First</li>') // inside, at start
$('.item').before('<p>Before</p>') // outside, before
$('.item').after('<p>After</p>') // outside, after
$('#container').html('<p>Replace all</p>') // replace contents
// Removal
$('.temp').remove() // removes element + event handlers
$('.temp').detach() // removes but keeps event handlers (reattach later)
$('.parent').empty() // removes children
// Dimensions & Position
$('.box').width() // content width
$('.box').outerWidth(true) // includes margin
$('.box').height()
$('.box').offset() // { top, left } relative to document
$('.box').position() // relative to offset parentEvents
// Bind events
$('#btn').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
console.log($(this).text()); // "this" = clicked element
});
// Shorthand methods
$('#btn').click(function() { ... });
$('#input').keyup(function(e) { console.log(e.key); });
$('#form').submit(function(e) { e.preventDefault(); });
$('.item').hover(
function() { $(this).addClass('hovered'); }, // mouseenter
function() { $(this).removeClass('hovered'); } // mouseleave
);
// Event delegation (handles dynamically added elements)
$(document).on('click', '.dynamic-btn', function() {
// works even for buttons added to DOM later
});
$('#list').on('click', 'li', function() {
$(this).toggleClass('done');
});
// Unbind events
$('#btn').off('click');
$('#btn').off('click', specificHandler);
// Trigger events
$('#btn').trigger('click');
$('#form').trigger('submit');
$('#input').trigger('focus');
// Custom events
$(document).on('dataLoaded', function(e, data) {
console.log(data);
});
$(document).trigger('dataLoaded', [{ items: [...] }]);