jQuery is a fast, small JavaScript library that simplifies HTML DOM traversal, event handling, effects, and AJAX. It uses a concise, CSS-like selector syntax to find elements and chain actions on them.
jQuery Introduction
1) How to Include jQuery
Use a CDN or host it locally. Place scripts before </body> or use defer.
<!-- CDN (recommended) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Local file (download jquery-3.6.0.min.js) -->
<script src="js/jquery-3.6.0.min.js"></script>
2) $(document).ready()
Run your code after the DOM is loaded.
<script>
$(document).ready(function(){
// safe to work with DOM here
});
</script>
3) Selectors (CSS-like)
Use $('selector') to grab elements quickly.
// id, class, tag
$('#title'); $('.item'); $('p');
// attribute + pseudo-like
$('input[type="text"]');
$('ul li:first');
4) Chaining
Call multiple methods in sequence on the same selection.
$('#box').addClass('active').slideDown(200).text('Ready!');
5) Events
Listen for user actions like click, input, keydown, etc.
$('#btn').on('click', function(){
alert('Clicked!');
});
6) Effects (Show/Hide, Fade, Slide)
Built-in animations are easy to use.
$('#box').hide();
$('#box').fadeIn(300);
$('#box').slideToggle(200);
7) DOM Manipulation
Read and change content, attributes, and classes.
$('#msg').text('Hello');
$('#link').attr('href', 'https://codingwithsonu.com');
$('#box').addClass('highlight');
8) AJAX (Load Data)
Load JSON or HTML without reloading the page.
$.getJSON('/api/users/1', function(data){
$('#user').text(data.name);
});
Note: AJAX requests require a server endpoint. In the editor, mock with a data URL or a local JSON file.
9) DOM Traversing
Move around the DOM from a given element.
$('.item.active').parent().find('.item').removeClass('active');
Tip: jQuery methods usually return the jQuery object, enabling powerful chaining.
If you’re maintaining older projects, jQuery is invaluable; for new projects, many tasks can also be done with modern vanilla JS.