Home > JQuery, Uncategorized > JQuery – Five useful tips

JQuery – Five useful tips

  1. Selectors
    Before an element can be manipulated using JQuery, it needs to be identified. JQuery provides a powerful syntax for selecting a one or more elements. Here are some simple selectors (notice similarity to CSS element selection):

    • Selecting by id: $(‘#yourelementid’)
    • Selecting by class name: $(‘.yourclassname’)
    • Selecting by tag name: $(‘p’) selects all the

      elements in the page

    Other useful selectors:

    • div > a will select all the links present directly inside a div tag
    • tag[attribute=value] will select all the elements of type tag with the given attribute name and value. For example input[type=’text’] will select all the text tags
    • :checkbox, :radio, :file are shortcuts to select checkboxes, radio buttons and file elements.
    • :hidden selects all the elements that are hidden (such as head and base tags). This DOES NOT select all the form hidden fields.
  2. Reading and Modifying attribute values
    Once a element is selected, its value can be read and modified using attr method, Here are examples:

    • $(‘base’).attr(“href”) reads the href attribute of the base tag
    • $(“#formTextId”).attr(“value”, ‘Test Value’);
  3. Document ready handler
    The document ready handler provides a convenient location to place all the document’s initialization code. JQuery executes this handler right after the browser finishes converting HTML into DOM tree. Here is the syntax for handler:

    $(document).ready(function() {
       // Your code

    A shortcut syntax for this:

     $(function() {
          // Your code

    It is possible to chain the several handlers and JQuery will execute them in the order in which they are declared.

  4. live() method
    JQuery’s live() method binds a handler to an event for current and future matched elements. This is extremely useful when elements are loaded dynamically (using AJAX for example) and need to have their behavior controlled by JQuery. For example the following code will display a “Print” window when a link of class printLink is clicked.

     $(".printLink").live("click", function(){
    	return false;	

    A JQuery plugin called Live Query provides a similar but more robust functionality

  5. load() method
    Provides a simple and convenient way to inject html content into an element (or set of elements) using Ajax. For example the following code injects html code of a

    element with id ‘paragraphId’ inside test.html page into div with id ‘someDivId’.
    $(‘#someDivId’).load(‘/test.html #paragraphId’);

Categories: JQuery, Uncategorized Tags:
  1. September 9th, 2009 at 09:10 | #1

    Hi! I was surfing and found your blog post… nice! I love your blog. 🙂 Cheers! Sandra. R.

  2. September 5th, 2011 at 10:42 | #2

    These tpocis are so confusing but this helped me get the job done.

  1. No trackbacks yet.