jQuery Syntax & Selectors

jQuery’s core pattern is: $(selector).action(). You first select elements (like CSS), then chain one or more actions (read/change content, styles, attributes, events, effects).

1) The $() Function & Document Ready

$ returns a jQuery object wrapping the matched elements. Run code after DOM loads.


<!-- include jQuery from CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
  $(document).ready(function(){
    $('p').css('color', 'green');
  });
</script>

2) Core Selectors

Use CSS-like selectors: ID #id, class .class, tag div, attribute, descendants, etc.


$('#title');         // id
$('.item');          // class
$('ul li.active'); // descendant + class
$('input[type="text"]'); // attribute

3) Filters & Pseudo-like Helpers

jQuery adds filters like :first, :last, :eq(n), :odd/:even, :contains().


$('li:first');      // first li
$('li:eq(2)');     // third li (0-based)
$('p:contains("Hello")');

4) Chaining Methods

Most methods return the same jQuery object, so you can chain many actions.


$('#box')
  .addClass('highlight')
  .text('Ready!')
  .slideDown(200);

5) Read/Write Content: .text(), .html(), .val()

.text() prints plain text, .html() parses HTML, .val() reads/writes form values.


$('#msg').text('Hello');             // plain text
$('#msg').html('<strong>Bold</strong>'); // HTML
$('#name').val('Sonu');               // input value

6) Attributes, CSS, and Classes

Get/set attributes and styles; add/remove/toggle classes.


$('#link').attr('href', 'https://codingwithsonu.com');
$('#box').css({ 'color': '#333', 'background': '#f7f7f7' });
$('#box').addClass('active').toggleClass('highlight');

7) Events: .on() & Shortcuts

Use .on('click', handler) for flexibility; you can also use shortcuts like .click(handler).


$('#btn').on('click', function(e){
  alert('Clicked!');
});
// shortcut:
$('#btn').click(function(){ console.log('ok'); });

8) Event Delegation & this

Bind to a parent for dynamic items; inside handlers, this is the DOM element (wrap with $(this)).


// Delegation: handle future .item elements
$('#list').on('click', '.item', function(){
  $(this).toggleClass('active');
});

9) Prevent Default & Stop Propagation

Stop link navigation or form submit; prevent event bubbling if needed.


$('a.block').on('click', function(e){
  e.preventDefault();  // cancel default action
  // e.stopPropagation(); // stop bubbling
});

10) Effects: Show/Hide, Fade, Slide

Animate visibility and height with built-ins; pass duration in ms and an optional callback.


$('#box').hide().fadeIn(400, function(){
  console.log('done');
});
$('#box').slideToggle(200);

11) DOM Traversing

Move in the DOM tree relative to the current selection.


$('.active').parent().find('.item').removeClass('active');
$('#start').closest('.card').find('.title').text('Updated');

12) Storing Data with .data()

Attach small pieces of data to elements without modifying attributes.


$('#user').data('id', 42);
const id = $('#user').data('id'); // 42

13) Avoid Conflicts: $.noConflict()

Release the $ alias if another library also uses it.


<script>
  var $j = jQuery.noConflict();
  $j(document).ready(function(){
    $j('p').text('Using $j instead of $');
  });
</script>
Tip: Prefer .on() + delegation for dynamic content; use .text() instead of .html() for untrusted input; batch DOM changes with chaining.