Buy quality & established websites

Aged, HIgh google PR and Alexa rank

Website Marketplace

desireweb buy sell website

Desire Website offers you a unique opportunity to buy high quality established business websites, ready to make money. We accept only high traffic, high google PR and popular established websites for our valued customers.
We offer you a FREE listing of your website for sale (one domain or website) for a limited time period. Other options are also at your disposition for a small fee (in order to maintain the website open to all 24 hours a day throughout the year). Hope you understand and help us to maintain our standard in order to help you make money using our service.
Desire Website is affiliated to high traffic website networks in order to attract more visitors through advertising and social networks. Please feel free to contact us if you need help.

Thank you for helping us to help you.

Useful tools for web developers

Improve your website’s performance, validate your code and more with these handy tools.

Life as a web developer may offer many rewards, but when project managers are asking you to do more and more in less and less time, it can becoming frustrating. So it’s always good to find tools that can make your work faster and more productive. Here we’ve gathered together some of the most useful.

Some you’ll have heard of, others you’ll already be using, but hopefully there’ll be at least one or two that can lighten your workload and brighten your day…

01. Firebug


Firefox add-on Firebug is a must-have for devs

From the developers at Firefox, the amazingly useful add-on Firebug enables you to debug, edit and monitor HTML, JavaScript and CSS live, all in the browser. One of the very best web development tools out there, this is a must-have for anyone working in web development.

02. HTML Entity Character Lookup

HTML Entity Character Lookup
HTML Entity Character Lookup helps you ensure all the characters on your page are validated

Using HTML entities is essential to ensure all the characters on your page are validated. However, often finding the right entity code requires scanning through 250 rows of characters. It’s also available as a widget on the Mac Dashboard.

03. Adobe Edge Inspect

Adobe Edge Inspect – for mobile developers
Adobe Edge Inspect is a modern alternative to Flash for mobile developers

This relatively new platform from Adobe gives developers a viable way to build interactive websites in the post-Flash era. With the aid of this tool, you can create mobile-ready and responsive apps and content using CSS and HTML that targets modern mobile and PC browsers.

04. -prefix-free

Prefix-free
-prefix-free helps you break free from CSS prefix hell

This cool tool from Lea Verou lets you use unprefixed CSS properties. It essentially works behind the scenes, adding the current browser’s prefix to any CSS code, only when it’s needed.

05. Cloud9 IDE

Cloud9 IDE
Cloud9 IDE enables developers around the world to edit the same code and chat together

Cloud9 IDE is a tool to help you collaborate with others on big-scale code projects. Letting developers around the world edit the same code and chat together in realtime, it’s fast emerging as one of the best browser-based IDEs. Features include code completion and editor, drop-document trees, smart drag and FTP integration.

06. PixelDropr

PixelDropr
PixelDropr is a great way to quickly create graphical website elements

This brilliant Photoshop plug-in helps you create a wide array of illustrations, buttons and icons easily. All these elements can then be dropped to any PSD file.

07. Foundation

Foundation3
Foundation 5 makes it “crazy fast” to code responsive designs, say its makers ZURB

Made by develpopers for developers at ZURB, this prototyping tool acts as a blueprint for your responsive design projects. Its latest version is an easy grid-structure that makes styling even more convenient and flexible. It works with both SASS and CSS.

08. Fontello

Fontello
Fontello offers an easy way to generate icons in web font form

This icon generator is truly one of a kind. Pick the icons you want and Fontello will compile them into customized web fonts. You can also edit and customize the symbol codes and names.

09. Cloud Comp

Cloud Comp
Share sites and apps with ease using Cloud Comp

This lightweight and easy to use tool helps you share website and apps with others. It’s been specifically built to give designers and developers a way to present comps to their clients inside of a realistic device shell.

10. BLOKK

BLOKK
BLOKK replaces dummy text with blocks

BLOKK is a fun-to-use font for “clients who do not understand Latin”. In other words, it replaces all text with blocks to suggest generic text instead. That way you can create good looking mock-ups and wireframes without confusing people with Lorem Ipsem.

11. Basecamp

Basecamp
Basecamp is the project management of choice for much of the web design industry

Developed by 37signals, Basecamp is a popular online tool to help you manage collaboration and project management with ease. It all runs in the cloud and most people working in web design and development will be familiar with it.

12. Browser Shots

Browser Shots
Browser Shots takes screenshots of your sites in different browsers

Browser Shots generates screenshots of how websites appear at 800×600 and 1024×768 resolution in six commonly used web browsers. Just submit the web address and a group of distributed computers will access and open it, then upload screenshots of the site for you to check out.

13. FavIcon Generator

FavIcon Generator
FavIcon Generator

A favicon (‘favorites icon’) is a small, 16×16 image that’s shown inside the browser’s location bar and bookmark menu when your site is called up. This tool makes it easy to create them for your site.

14. Web-developer toolbar

Web-developer toolbar
The Web Developer extension adds a range of handy tools to the browser

This Firefox plug-in feature provides a number of useful tools that web developers use on a day-to-day basis. It’s particularly useful when inspecting your HTTP header information or when you need to validate your XHTML.

15. Load Impact

Load Impact
Load Impact simulates large amounts of traffic to test your site’s performance

A successful website is one that loads faster and quickly. Load Impact is a cloud-based service for load testing and website optimization that generates traffic load by simulating users. In other words it lets you test how your website, web app, mobile app or API will perform with up to 1.2 million concurrent users.

16. Lorem Ipsum Generator

Lorem Ipsum Generator
Lorem Ipsum Generator does exactly what you’d expect

If you’re not impressed with BLOKK (see 10) and want to stick with Lorem Ipsum, this reference site about the subject, giving information on its origins, also includes a random Lorem Ipsum generator.

17. W3c Markup Validation Service

W3c Markup Validation Service
W3c Markup Validation Service checks your documents for conformance to the relevant specification

Validating web documents is an important step that can dramatically help improving and ensuring their quality. This free service from the W3C helps you to check the markup validity of different web documents, in HTML, SMIL, XHTML and MathML and more.

18. Typetester

Typetester
Take fonts for a spin with Typetester

The Typetester is a browser tool for comparing different kinds of fonts, Choose the typeface you want to test out, along with your chosen size, tracking, colour etc, and Typetester applies it to a set piece of text so you can see what it will look like.

19. Pingdom

Pingdom
Pingdom is a great tool for monitoring your site’s performance

Pingdom is a service that tracks the uptime, downtime, and performance of websites. Upload a full page in HTML and it will mimic the loading process of the entire website, incorporating all the elements (namely JavaScript, RSS, CSS and images), thereby enabling you to check and monitor the efficiency of your site.

20. CSS Sprite Generator

CSS Sprite Generator
CSS Sprite Generator can help improve your site’s performance

By reducing the number of HTTP requests, this tool aims at increasing the loading speed of your website. Images are combined into one larger image at defined X and Y coorindates. Having assigned this generated image to relevant page elements the background-position CSS property can then be used to shift the visible area to the required component image.

Words: Ananya Srivastava

Ananya Srivastava is a writer working with EnablingBiz eSolutions, whihc offers internet marketing, web design and development services, as well as white-label services to design and development firms in North America and Europe. Join them on Google+.

Front-End Developer Tools – Editors Choice

This is a tech post by Arnaud Breton, full-stack developer here at mention with a specific focus on the front-end side and user experience. Before joining mention, Arnaud was co-founder and CTO of UniShared and VideoNot.es, part of the Imagine K-12 2013 Winter batch.

Over the last few years, we’ve seen tremendous growth in an entirely new generation of web applications. These apps have become much richer, leading to a huge increase in complexity on the front-end side.

Frameworks like Backbone (the one we use at mention), AngularJS, and EmberJS provide robust solutions to build amazing apps, leveraging all of the web’s power. Meanwhile, Javascript, the web language, has grown a lot (both in popularity and in maturity) and now has back-end side implementation with NodeJS.

In order to succeed in these new challenges of complexity, developers have created a lot of tools to streamline the overall development process. From test frameworks to profiling tools, we now have mature and useful tools to bring the best experience to our users.

At mention, we love the tools which help us to provide the best quality software while at the same time making our life easier. In this blogpost, we’ll present the 5 best tools and frameworks that we use every day to address these challenges.

Chrome dev tools

The best tool we have in our hands today. Since its birth, Chrome has invested a lot in its developer tools and is still improving them continuously. Each release (every 6 weeks or so) comes with its own brand new dev tool features.

The dev tools are a complete suite of diverse instruments. You can edit the DOM (HTML)/CSS in real-time, debug Javascript step by step while undertaking a deep performance analysis, even add a terminal. We recently solved some render performance issue thanks to this.

The DOM/CSS editor is an extremely powerful tool, letting you provide realtime feedback to your team, iterating fast on the UI/UX of a new feature.

The official website and the Google Developers Youtube channel both are goldmines of information. For example, the section about command-line API contains really useful commands.
You can for example copy anything to your clipboard from the console by calling the special `copy` function and pass the thing to be copied (object, function return, etc.)

A lot of great tutorials are also available on HTML5 Rocks.

On top of all this, the network tools let you understand what is really going on under the hood and optimize your loading flows, all while the timeline gives you a deeper view of what the browser does.

If you’re curious enough (like us) you can learn a lot about how a browser (and indirectly, the web) is working, letting you take back full control of your application’s lifecycle.

I personally think that if they continue to follow this path, they will definitely become the ultimate IDE (or Integrated Developer Environment) for the web[a] offering web developers a powerful development space bundled directly into the browser.

Grunt

Grunt is our preferred tool when it comes to task automation. It’s a Javascript task runner, offering both a lot of bundled plugins for common tasks, while still being very extensible, giving you the option to write all kinds of tasks to suit your need. The best comes when you can combine tasks together to create even more powerful ones!

We also used it to create a workaround for some performance issues we found in the Vagrant rsync-auto watcher, which were recently introduced.   Grunt offers a wide variety of plugins, ranging fromwatching files to linting, compiling, and minifying your code. Its syntax is consistent and easy to learn and a lot of examples are available around the Web.

LiveReload

How many times on average do you hit the refresh key on your keyboard every day? A lot, right?   LiveReload is a simple Web protocol that triggers events to the clients whenever files are modified. Clients can handle this event in their own way, even if the most common use case is when a file is modified (or is a compiled version).   The client/server come in various implementations. We personally use the one bundled in the Grunt watcher plugin, as well as this simple Chrome extension as a client (which has the advantage of being switchable, because you don’t always want live reload, after all).   You can see it in action here:https://www.youtube.com/watch?v=wCVwdvufTds   Talking about Chrome extensions, theChrome store is full of powerful ones. Go and explore, and you’re sure to discover things that will make your life far more easier.   Here are some of our favorite ones:

        • WhatFont, which lets you discover the rendered font of any element on any website (useful when looking for the perfect typography you saw on another site, or for debugging your font-face styles).

 

 

      • Page ruler: another useful one, mainly because just like any front-end developer, you’re obsessed by pixel perfection, right?

 

 

      • Proxy SwitchySharp can also be of great help when it comes to debugging localized information (default currency, phone numbers, etc).

 

 

 

 

Mocha / Chai / Sinon

Does testing make you queasy? It’s often the case, mainly because it requires a ton of bootstrapping and if you don’t design things to be testable from the beginning, things can become very hard.   Fortunately, we now have great testing frameworks, as powerful as what you may have already used with other languages.   The two main frameworks today areJasmine and Mocha. I personally have had experience with both in the past and have finally come to choose the latter — Mocha. The main advantage comes when you work with a lot of asynchronous code, a common use-case when developing in Javascript.   For instance, please consider this really simple example:   Here’s now two different specs, one written with Jasmine, the other with Mocha/Chai:   The chosen syntax for Jasmine is the default one,described in the official documentation. This unofficial extension enhances Jasmine async feature to provide the same thing that Mocha. Take few minutes to understand this sample and observe how clearer is the Mocha syntax. Unlike Jasmine, Mocha offers only the behavior testing structure (more about BDD), and not the assertion/mock framework. But there’s nothing bad here, since it perfectly integrates with dedicated frameworks like Chai and Sinon.Sinon comes with a full-set of functions to easily mock objects and stub methods. For example, here’s how you can assess that a method has been called using the Sinon’s spy type (taken from the excellent documentation):

1234567891011121314151617181920
// Function under test
function once(fn) {
var returnValue, called = false;
return function () {
if (!called) {
called = true;
returnValue = fn.apply(this, arguments);
}
return returnValue;
};
}
it(calls the original function, function () {
var spy = sinon.spy();
var proxy = once(spy);
proxy();
assert(spy.called);
});
view rawsinon.js hosted with ❤ by GitHub

Chai is remarkable in the way that it lets you make assertions in a very similar way to natural language. For instance, please consider the following example, leveraging the should assertion syntax:

Very clear, right? No reason not to go testing your code now!

Karma

Last but not the least, Karma (ex Testacular) is a Javascript test runner written by the guys behind AngularJS. Now that you’re enjoying writing tests with Mocha, Chai, and Sinon, what about running them continuously, providing you with realtime feedback?

Karma lets you execute your tests from your workstation (in continuous mode) to the production CI. It can launch multiple browsers (Chrome, Firefox, IE (!), PhantomJS, etc.) and run your tests against them, giving you maximum confidence in your code.

While developing, it’s a real pleasure to write code on your first monitor and get the results, in real-time, on the second, all running against multiple browsers.

You’re now good to go to become a front-end ninja, ready to beat all the adversity that you’ll meet during your journey.

Of course, we didn’t even mention here any text editors (we use both Sublime Text and Vim at mention), roots of all our productivity!

All the samples are available on GitHub Gist. Of course, feel free to play with it!

And you, what are your favourite tools when it comes to Front-end development?

jQuery – Effects

jQuery provides a trivially simple interface for doing various kind of amazing effects. jQuery methods allow us to quickly apply commonly used effects with a minimum configuration.

This tutorial covers all the important jQuery methods to create visual effects.

Showing and Hiding elements:

The commands for showing and hiding elements are pretty much what we would expect: show()to show the elements in a wrapped set and hide() to hide them.

Syntax:

Here is the simple syntax for show() method:

[selector].show( speed, [callback] );

Here is the description of all the parameters:

  • speed: A string representing one of the three predefined speeds (“slow”, “normal”, or “fast”) or the number of milliseconds to run the animation (e.g. 1000).
  • callback: This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.

Following is the simple syntax for hide() method:

[selector].hide( speed, [callback] );

Here is the description of all the parameters:

  • speed: A string representing one of the three predefined speeds (“slow”, “normal”, or “fast”) or the number of milliseconds to run the animation (e.g. 1000).
  • callback: This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.

Example:

Consider the following HTML file with a small JQuery coding:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

     $("#show").click(function () {
        $(".mydiv").show( 1000 );
     });

     $("#hide").click(function () {
        $(".mydiv").hide( 1000 );
     });

   });

   </script>
   <style>
   .mydiv{ margin:10px;padding:12px;
      border:2px solid #666;
      width:100px;
      height:100px;
    }
  </style>
</head>
<body>
   <div class="mydiv">
      This is  SQUAR
   </div>

   <input id="hide" type="button" value="Hide" />   
   <input id="show" type="button" value="Show" />   

</body>
</html>

To understand it in better way you can Try it yourself.

Toggling the elements:

jQuery provides methods to toggle the display state of elements between revealed or hidden. If the element is initially displayed, it will be hidden; if hidden, it will be shown.

Syntax:

Here is the simple syntax for one of the toggle() methods:

[selector]..toggle([speed][, callback]);

Here is the description of all the parameters:

  • speed: A string representing one of the three predefined speeds (“slow”, “normal”, or “fast”) or the number of milliseconds to run the animation (e.g. 1000).
  • callback: This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.

Example:

We can animate any element, such as a simple <div> containing an image:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $(".clickme").click(function(event){
          $(".target").toggle('slow', function(){
             $(".log").text('Transition Complete');
          });
      });

   });
   </script>
   <style>
   .clickme{ margin:10px;padding:12px;
      border:2px solid #666;
      width:100px;
      height:50px;
    }
   </style>
</head>
<body>
   <div class="content">
      <div class="clickme">Click Me</div>
      <div class="target">
         <img src="/images/jquery.jpg" alt="jQuery" />
      </div>
      <div class="log"></div>
</body>
</html>

To understand it in better way you can Try it yourself.

JQuery Effect Methods:

You have seen basic concept of jQuery Effects. Following table lists down all the important methods to create different kind of effects:

Methods and Description
animate( params, [duration, easing, callback] )
A function for making custom animations.
fadeIn( speed, [callback] )
Fade in all matched elements by adjusting their opacity and firing an optional callback after completion.
fadeOut( speed, [callback] )
Fade out all matched elements by adjusting their opacity to 0, then setting display to “none” and firing an optional callback after completion.
fadeTo( speed, opacity, callback )
Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion.
hide( )
Hides each of the set of matched elements if they are shown.
hide( speed, [callback] )
Hide all matched elements using a graceful animation and firing an optional callback after completion.
show( )
Displays each of the set of matched elements if they are hidden.
show( speed, [callback] )
Show all matched elements using a graceful animation and firing an optional callback after completion.
slideDown( speed, [callback] )
Reveal all matched elements by adjusting their height and firing an optional callback after completion.
slideToggle( speed, [callback] )
Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion.
slideUp( speed, [callback] )
Hide all matched elements by adjusting their height and firing an optional callback after completion.
stop( [clearQueue, gotoEnd ])
Stops all the currently running animations on all the specified elements.
toggle( )
Toggle displaying each of the set of matched elements.
toggle( speed, [callback] )
Toggle displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion.
toggle( switch )
Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements).
jQuery.fx.off
Globally disable all animations.

UI Library Based Effects:

To use these effects you would have to download jQuery UI Library jquery-ui-1.7.2.custom.min.js or latest version of this UI library from jQuery UI Library.

After extracting jquery-ui-1.7.2.custom.min.js file from the download, you would include this file in similar way as you include core jQuery Library file.

Methods and Description
Blind
Blinds the element away or shows it by blinding it in.
Bounce
Bounces the element vertically or horizontally n-times.
Clip
Clips the element on or off, vertically or horizontally.
Drop
Drops the element away or shows it by dropping it in.
Explode
Explodes the element into multiple pieces.
Fold
Folds the element like a piece of paper.
Highlight
Highlights the background with a defined color.
Puff
Scale and fade out animations create the puff effect.
Pulsate
Pulsates the opacity of the element multiple times.
Scale
Shrink or grow an element by a percentage factor.
Shake
Shakes the element vertically or horizontally n-times.
Size
Resize an element to a specified width and height.
Slide
Slides the element out of the viewport.
Transfer
Transfers the outline of an element to another.

 

jQuery – Events Handling

We have the ability to create dynamic web pages by using events. Events are actions that can be detected by your Web Application.

Following are the examples events:

  • A mouse click
  • A web page loading
  • Taking mouse over an element
  • Submitting an HTML form
  • A keystroke on your keyboard
  • etc.

When these events are triggered you can then use a custom function to do pretty much whatever you want with the event. These custom functions call Event Handlers.

Binding event handlers:

Using the jQuery Event Model, we can establish event handlers on DOM elements with the bind()method as follows:

$('div').bind('click', function( event ){
   alert('Hi there!');
});

This code will cause the division element to respond to the click event; when a user clicks inside this division thereafter, the alert will be shown. Try it yourself.

The full syntax of the bind() command is as follows:

selector.bind( eventType[, eventData], handler)

Following is the description of the parameters:

  • eventType: A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.
  • eventData: This is optional parameter is a map of data that will be passed to the event handler.
  • handler: A function to execute each time the event is triggered.

Removing event handlers:

Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler.

jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows:

selector.unbind(eventType, handler)

or 

selector.unbind(eventType)

Following is the description of the parameters:

  • eventType: A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.
  • handler: If provided, identifies the specific listener that.s to be removed.

Event Types:

The following are cross platform and recommended event types which you can bind using JQuery:

Event Type Description
blur Occurs when the element loses focus
change Occurs when the element changes
click Occurs when a mouse click
dblclick Occurs when a mouse double-click
error Occurs when there is an error in loading or unloading etc.
focus Occurs when the element gets focus
keydown Occurs when key is pressed
keypress Occurs when key is pressed and released
keyup Occurs when key is released
load Occurs when document is loaded
mousedown Occurs when mouse button is pressed
mouseenter Occurs when mouse enters in an element region
mouseleave Occurs when mouse leaves an element region
mousemove Occurs when mouse pointer moves
mouseout Occurs when mouse pointer moves out of an element
mouseover Occurs when mouse pointer moves over an element
mouseup Occurs when mouse button is released
resize Occurs when window is resized
scroll Occurs when window is scrolled
select Occurs when a text is selected
submit Occurs when form is submitted
unload Occurs when documents is unloaded

The Event Object:

The callback function takes a single parameter; when the handler is called the JavaScript event object will be passed through it.

The event object is often unneccessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certail attributes which you would need to be accessed.

The Event Attributes:

The following event properties/attributes are available and safe to access in a platform independent manner:

Property Description
altKey Set to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards.
ctrlKey Set to true if the Ctrl key was pressed when the event was triggered, false if not.
data The value, if any, passed as the second parameter to the bind() command when the handler was established.
keyCode For keyup and keydown events, this returns the key that was pressed.
metaKey Set to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the Ctrl key on PCs and the Command key on Macs.
pageX For mouse events, specifies the horizontal coordinate of the event relative from the page origin.
pageY For mouse events, specifies the vertical coordinate of the event relative from the page origin.
relatedTarget For some mouse events, identifies the element that the cursor left or entered when the event was triggered.
screenX For mouse events, specifies the horizontal coordinate of the event relative from the screen origin.
screenY For mouse events, specifies the vertical coordinate of the event relative from the screen origin.
shiftKey Set to true if the Shift key was pressed when the event was triggered, false if not.
target Identifies the element for which the event was triggered.
timeStamp The timestamp (in milliseconds) when the event was created.
type For all events, specifies the type of event that was triggered (for example, click).
which For keyboard events, specifies the numeric code for the key that caused the event, and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right)

To understand it in better way you can Try it yourself.

The Event Methods:

There is a list of methods which can be called on an Event Object:

Method Description
preventDefault() Prevents the browser from executing the default action.
isDefaultPrevented() Returns whether event.preventDefault() was ever called on this event object.
stopPropagation() Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.
isPropagationStopped() Returns whether event.stopPropagation() was ever called on this event object.
stopImmediatePropagation() Stops the rest of the handlers from being executed.
isImmediatePropagationStopped() Returns whether event.stopImmediatePropagation() was ever called on this event object.

Event Manipulation Methods:

Following table lists down important event-related methods:

Method Description
bind( type, [data], fn ) Binds a handler to one or more events (like click) for each matched element. Can also bind custom events.
die( type, fn ) This does the opposite of live, it removes a bound live event.
hover( over, out ) Simulates hovering for example moving the mouse on, and off, an object.
live( type, fn ) Binds a handler to an event (like click) for all current – and future – matched element. Can also bind custom events.
one( type, [data], fn ) Binds a handler to one or more events to be executed once for each matched element.
ready( fn ) Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.
toggle( fn, fn2, fn3,… ) Toggle among two or more function calls every other click.
trigger( event, [data] ) Trigger an event on every matched element.
triggerHandler( event, [data] ) Triggers all bound event handlers on an element .
unbind( [type], [fn] ) This does the opposite of bind, it removes bound events from each of the matched elements.

Event Helper Methods:

jQuery also provides a set of event helper functions which can be used either to trigger an event to bind any event types mentioned above.

Trigger Methods:

Following is an example which would triggers the blur event on all paragraphs:

$("p").blur();

Binding Methods:

Following is an example which would bind a click event on all the <div>:

$("div").click( function () { 
   // do something here
});

To understand it in better way you can Try it yourself.

Here is a complete list of all the support methods provided by jQuery:

Method Description
blur( ) Triggers the blur event of each matched element.
blur( fn ) Bind a function to the blur event of each matched element.
change( ) Triggers the change event of each matched element.
change( fn ) Binds a function to the change event of each matched element.
click( ) Triggers the click event of each matched element.
click( fn ) Binds a function to the click event of each matched element.
dblclick( ) Triggers the dblclick event of each matched element.
dblclick( fn ) Binds a function to the dblclick event of each matched element.
error( ) Triggers the error event of each matched element.
error( fn ) Binds a function to the error event of each matched element.
focus( ) Triggers the focus event of each matched element.
focus( fn ) Binds a function to the focus event of each matched element.
keydown( ) Triggers the keydown event of each matched element.
keydown( fn ) Bind a function to the keydown event of each matched element.
keypress( ) Triggers the keypress event of each matched element.
keypress( fn ) Binds a function to the keypress event of each matched element.
keyup( ) Triggers the keyup event of each matched element.
keyup( fn ) Bind a function to the keyup event of each matched element.
load( fn ) Binds a function to the load event of each matched element.
mousedown( fn ) Binds a function to the mousedown event of each matched element.
mouseenter( fn ) Bind a function to the mouseenter event of each matched element.
mouseleave( fn ) Bind a function to the mouseleave event of each matched element.
mousemove( fn ) Bind a function to the mousemove event of each matched element.
mouseout( fn ) Bind a function to the mouseout event of each matched element.
mouseover( fn ) Bind a function to the mouseover event of each matched element.
mouseup( fn ) Bind a function to the mouseup event of each matched element.
resize( fn ) Bind a function to the resize event of each matched element.
scroll( fn ) Bind a function to the scroll event of each matched element.
select( ) Trigger the select event of each matched element.
select( fn ) Bind a function to the select event of each matched element.
submit( ) Trigger the submit event of each matched element.
submit( fn ) Bind a function to the submit event of each matched element.
unload( fn ) Binds a function to the unload event of each matched element.

 

jQuery – DOM Manipulation Methods

JQuery provides methods to manipulate DOM in efficient way. You do not need to write big code to modify the value of any element’s attribute or to extract HTML code from a paragraph or division.

JQuery provides methods such as .attr(), .html(), and .val() which act as getters, retrieving information from DOM elements for later use.

Content Manipulation:

The html( ) method gets the html contents (innerHTML) of the first matched element.

Here is the syntax for the method:

selector.html( )

Example:

Following is an example which makes use of .html() and .text(val) methods. Here .html() retrieves HTML content from the object and then .text( val ) method sets value of the object using passed parameter:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

     $("div").click(function () {
      var content = $(this).html();
      $("#result").text( content );
    });

   });

   </script>
   <style>
      #division{ margin:10px;padding:12px;
                 border:2px solid #666;
                 width:60px;
               }
  </style>
</head>
<body>
   <p>Click on the square below:</p>
   <span id="result"> </span>
   <div id="division" style="background-color:blue;">
     This is Blue Square!!
   </div>
</body>
</html>

To understand it in better way you can Try it yourself.

DOM Element Replacement:

You can replace a complete DOM element with the specified HTML or DOM elements. ThereplaceWith( content ) method serves this purpose very well.

Here is the syntax for the method:

selector.replaceWith( content )

Here content is what you want to have instead of original element. This could be HTML or simple text.

Example:

Following is an example which would replace division element with “<h1>JQuery is Great</h1>”:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

     $("div").click(function () {
       $(this).replaceWith("<h1>JQuery is Great</h1>");
    });

   });

   </script>
   <style>
      #division{ margin:10px;padding:12px;
                 border:2px solid #666;
                 width:60px;
               }
  </style>
</head>
<body>
   <p>Click on the square below:</p>
   <span id="result"> </span>
   <div id="division" style="background-color:blue;">
     This is Blue Square!!
   </div>
</body>
</html>

To understand it in better way you can Try it yourself.

Removing DOM Elements:

There may be a situation when you would like to remove one or more DOM elements from the document. JQuery provides two methods to handle the situation.

The empty( ) method remove all child nodes from the set of matched elements where as the method remove( expr ) method removes all matched elements from the DOM.

Here is the syntax for the method:

selector.remove( [ expr ])

or 

selector.empty( )

You can pass optional paramter expr to filter the set of elements to be removed.

Example:

Following is an example where elements are being removed as soon as they are clicked:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

     $("div").click(function () {
       $(this).remove( );
    });

   });

   </script>
   <style>
      .div{ margin:10px;padding:12px;
             border:2px solid #666;
             width:60px;
           }
  </style>
</head>
<body>
   <p>Click on any square below:</p>
   <span id="result"> </span>
   <div class="div" style="background-color:blue;"></div>
   <div class="div" style="background-color:green;"></div>
   <div class="div" style="background-color:red;"></div>
</body>
</html>

To understand it in better way you can Try it yourself.

Inserting DOM elements:

There may be a situation when you would like to insert new one or more DOM elements in your existing document. JQuery provides various methods to insert elements at various locations.

The after( content ) method insert content after each of the matched elements where as the method before( content ) method inserts content before each of the matched elements.

Here is the syntax for the method:

selector.after( content )

or

selector.before( content )

Here content is what you want to insert. This could be HTML or simple text.

Example:

Following is an example where <div> elements are being inserted just before the clicked element:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

     $("div").click(function () {
       $(this).before('<div class="div"></div>' );
    });

   });

   </script>
   <style>
      .div{ margin:10px;padding:12px;
             border:2px solid #666;
             width:60px;
           }
  </style>
</head>
<body>
   <p>Click on any square below:</p>
   <span id="result"> </span>
   <div class="div" style="background-color:blue;"></div>
   <div class="div" style="background-color:green;"></div>
   <div class="div" style="background-color:red;"></div>
</body>
</html>

To understand it in better way you can Try it yourself.

DOM Manipulation Methods:

Following table lists down all the methods which you can use to manipulate DOM elements:

Method Description
after( content ) Insert content after each of the matched elements.
append( content ) Append content to the inside of every matched element.
appendTo( selector ) Append all of the matched elements to another, specified, set of elements.
before( content ) Insert content before each of the matched elements.
clone( bool ) Clone matched DOM Elements, and all their event handlers, and select the clones.
clone( ) Clone matched DOM Elements and select the clones.
empty( ) Remove all child nodes from the set of matched elements.
html( val ) Set the html contents of every matched element.
html( ) Get the html contents (innerHTML) of the first matched element.
insertAfter( selector ) Insert all of the matched elements after another, specified, set of elements.
insertBefore( selector ) Insert all of the matched elements before another, specified, set of elements.
prepend( content ) Prepend content to the inside of every matched element.
prependTo( selector ) Prepend all of the matched elements to another, specified, set of elements.
remove( expr ) Removes all matched elements from the DOM.
replaceAll( selector ) Replaces the elements matched by the specified selector with the matched elements.
replaceWith( content ) Replaces all matched elements with the specified HTML or DOM elements.
text( val ) Set the text contents of all matched elements.
text( ) Get the combined text contents of all matched elements.
wrap( elem ) Wrap each matched element with the specified element.
wrap( html ) Wrap each matched element with the specified HTML content.
wrapAll( elem ) Wrap all the elements in the matched set into a single wrapper element.
wrapAll( html ) Wrap all the elements in the matched set into a single wrapper element.
wrapInner( elem ) Wrap the inner child contents of each matched element (including text nodes) with a DOM element.
wrapInner( html ) Wrap the inner child contents of each matched element (including text nodes) with an HTML structure.

 

jQuery – CSS Methods

The jQuery library supports nearly all of the selectors included in Cascading Style Sheet (CSS) specifications 1 through 3, as outlined on the World Wide Web Consortium’s site.

Using JQuery library developers can enhance their websites without worrying about browsers and their versions as long as the browsers have JavaScript enabled.

Most of the JQuery CSS Methods do not modify the content of the jQuery object and they are used to apply CSS properties on DOM elements.

Apply CSS Properties:

This is very simple to apply any CSS property using JQuery method css( PropertyName, PropertyValue ).

Here is the syntax for the method:

selector.css( PropertyName, PropertyValue );

Here you can pass PropertyName as a javascript string and based on its value, PropertyValuecould be string or integer.

Example:

Following is an example which adds font color to the second list item.

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {
      $("li").eq(2).css("color", "red");
   });

   </script>
</head>
<body>
   <div>
   <ul>
     <li>list item 1</li>
     <li>list item 2</li>
     <li>list item 3</li>
     <li>list item 4</li>
     <li>list item 5</li>
     <li>list item 6</li>
   </ul>
   </div>
</body>
</html>

To understand it in better way you can Try it yourself.

Apply Multiple CSS Properties:

You can apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2….). You can apply as many properties as you like in a single call.

Here is the syntax for the method:

selector.css( {key1:val1, key2:val2....keyN:valN})

Here you can pass key as property and val as its value as described above.

Example:

Following is an example which adds font color as well as background color to the second list item.

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {
      $("li").eq(2).css({"color":"red", 
                         "background-color":"green"});
   });

   </script>
</head>
<body>
   <div>
   <ul>
     <li>list item 1</li>
     <li>list item 2</li>
     <li>list item 3</li>
     <li>list item 4</li>
     <li>list item 5</li>
     <li>list item 6</li>
   </ul>
   </div>
</body>
</html>

To understand it in better way you can Try it yourself.

Setting Element Width & Height:

The width( val ) and height( val ) method can be used to set the width and hieght respectively of any element.

Example:

Following is a simple example which sets the width of first division element where as rest of the elements have width set by style sheet:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {
      $("div:first").width(100);
      $("div:first").css("background-color", "blue");
   });

   </script>
   <style>
   div{ width:70px; height:50px; float:left; margin:5px;
      background:red; cursor:pointer; }
  </style>
</head>
<body>
  <div></div>
  <div>d</div>
  <div>d</div>
  <div>d</div>
  <div>d</div>
</body>
</html>

To understand it in better way you can Try it yourself.

JQuery CSS Methods:

Following table lists down all the methods which you can use to play with CSS properties:

Method Description
css( name ) Return a style property on the first matched element.
css( name, value ) Set a single style property to a value on all matched elements.
css( properties ) Set a key/value object as style properties to all matched elements.
height( val ) Set the CSS height of every matched element.
height( ) Get the current computed, pixel, height of the first matched element.
innerHeight( ) Gets the inner height (excludes the border and includes the padding) for the first matched element.
innerWidth( ) Gets the inner width (excludes the border and includes the padding) for the first matched element.
offset( ) Get the current offset of the first matched element, in pixels, relative to the document
offsetParent( ) Returns a jQuery collection with the positioned parent of the first matched element.
outerHeight( [margin] ) Gets the outer height (includes the border and padding by default) for the first matched element.
outerWidth( [margin] ) Get the outer width (includes the border and padding by default) for the first matched element.
position( ) Gets the top and left position of an element relative to its offset parent.
scrollLeft( val ) When a value is passed in, the scroll left offset is set to that value on all matched elements.
scrollLeft( ) Gets the scroll left offset of the first matched element.
scrollTop( val ) When a value is passed in, the scroll top offset is set to that value on all matched elements.
scrollTop( ) Gets the scroll top offset of the first matched element.
width( val ) Set the CSS width of every matched element.
width( ) Get the current computed, pixel, width of the first matched element.

 

jQuery – DOM Traversing

jQuery is a very powerful tool which provides a variety of DOM traversal methods to help us select elements in a document randomly as well as in sequential method.

Most of the DOM Traversal Methods do not modify the jQuery object and they are used to filter out elements from a document based on given conditions.

Find Elements by index:

Consider a simple document with the following HTML content:

<html>
<head>
<title>the title</title>
</head>
<body>
   <div>
   <ul>
     <li>list item 1</li>
     <li>list item 2</li>
     <li>list item 3</li>
     <li>list item 4</li>
     <li>list item 5</li>
     <li>list item 6</li>
   </ul>
   </div>
</body>
</html>
  • Above every list has its own index, and can be located directly by using eq(index)method as below example.
  • Every child element starts its index from zero, thus, list item 2 would be accessed by using $(“li”).eq(1) and so on.

Example:

Following is a simple example which adds the color to second list item.

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {
      $("li").eq(2).addClass("selected");
   });

   </script>
   <style>
      .selected { color:red; }
  </style>
</head>
<body>
   <div>
   <ul>
     <li>list item 1</li>
     <li>list item 2</li>
     <li>list item 3</li>
     <li>list item 4</li>
     <li>list item 5</li>
     <li>list item 6</li>
   </ul>
   </div>
</body>
</html>

To understand it in better way you can Try it yourself.

Filtering out Elements:

The filter( selector ) method can be used to filter out all elements from the set of matched elements that do not match the specified selector(s). The selector can be written using any selector syntax.

Example:

Following is a simple example which applies color to the lists associated with middle class:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {
      $("li").filter(".middle").addClass("selected");
   });

   </script>
   <style>
      .selected { color:red; }
  </style>
</head>
<body>
   <div>
   <ul>
     <li class="top">list item 1</li>
     <li class="top">list item 2</li>
     <li class="middle">list item 3</li>
     <li class="middle">list item 4</li>
     <li class="bottom">list item 5</li>
     <li class="bottom">list item 6</li>
   </ul>
   </div>
</body>
</html>

To understand it in better way you can Try it yourself.

Locating Descendent Elements :

The find( selector ) method can be used to locate all the descendent elements of a particular type of elements. The selector can be written using any selector syntax.

Example:

Following is an example which selects all the <span> elements available inside different <p> elements:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("p").find("span").addClass("selected");
   });

   </script>
   <style>
      .selected { color:red; }
  </style>
</head>
<body>
   <p>This is 1st paragraph and <span>THIS IS RED</span></p>
   <p>This is 2nd paragraph and <span>THIS IS ALSO RED</span></p>
</body>
</html>

To understand it in better way you can Try it yourself.

JQuery DOM Traversing Methods:

Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements:

Selector Description
eq( index ) Reduce the set of matched elements to a single element.
filter( selector ) Removes all elements from the set of matched elements that do not match the specified selector(s).
filter( fn ) Removes all elements from the set of matched elements that do not match the specified function.
is( selector ) Checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector.
map( callback ) Translate a set of elements in the jQuery object into another set of values in a jQuery array (which may, or may not contain elements).
not( selector ) Removes elements matching the specified selector from the set of matched elements.
slice( start, [end] ) Selects a subset of the matched elements.

Following table lists down other useful methods which you can use to locate various elements in a DOM:

Selector Description
add( selector ) Adds more elements, matched by the given selector, to the set of matched elements.
andSelf( ) Add the previous selection to the current selection.
children( [selector]) Get a set of elements containing all of the unique immediate children of each of the matched set of elements.
closest( selector ) Get a set of elements containing the closest parent element that matches the specified selector, the starting element included.
contents( ) Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
end( ) Revert the most recent ‘destructive’ operation, changing the set of matched elements to its previous state .
find( selector ) Searches for descendent elements that match the specified selectors.
next( [selector] ) Get a set of elements containing the unique next siblings of each of the given set of elements.
nextAll( [selector] ) Find all sibling elements after the current element.
offsetParent( ) Returns a jQuery collection with the positioned parent of the first matched element.
parent( [selector] ) Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements.
parents( [selector] ) Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).
prev( [selector] ) Get a set of elements containing the unique previous siblings of each of the matched set of elements.
prevAll( [selector] ) Find all sibling elements in front of the current element.
siblings( [selector] ) Get a set of elements containing all of the unique siblings of each of the matched set of elements.

 

jQuery – DOM Attributes

Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements.

Most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are:

  • className
  • tagName
  • id
  • href
  • title
  • rel
  • src

Consider the following HTML markup for an image element:

<img id="myImage" src="image.gif" alt="An image" 
class="someClass" title="This is an image"/>

In this element’s markup, the tag name is img, and the markup for id, src, alt, class, and title represents the element’s attributes, each of which consists of a name and a value.

jQuery gives us the means to easily manipulate an element’s attributes and gives us access to the element so that we can also change its properties.

Get Attribute Value:

The attr() method can be used to either fetch the value of an attribute from the first element in the matched set or set attribute values onto all matched elements.

Example:

Following is a simple example which fetches title attribute of <em> tag and set <div id=”divid”> value with the same value:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      var title = $("em").attr("title");
      $("#divid").text(title);
   });

   </script>
</head>
<body>
   <div>
      <em title="Bold and Brave">This is first paragraph.</em>
      <p id="myid">This is second paragraph.</p>
      <div id="divid"></div>
   </div>
</body>
</html>

To understand it in better way you can Try it yourself.

Set Attribute Value:

The attr(name, value) method can be used to set the named attribute onto all elements in the wrapped set using the passed value.

Example:

Following is a simple example which set src attribute of an image tag to a correct location:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("#myimg").attr("src", "/images/jquery.jpg");
   });

   </script>
</head>
<body>
   <div>
      <img id="myimg" src="/wongpath.jpg" alt="Sample image" />
   </div>
</body>
</html>

To understand it in better way you can Try it yourself.

Applying Styles:

The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space.

Example:

Following is a simple example which sets class attribute of a para <p> tag:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("em").addClass("selected");
      $("#myid").addClass("highlight");
   });

   </script>
   <style>
      .selected { color:red; }
      .highlight { background:yellow; }
  </style>
</head>
<body>
   <em title="Bold and Brave">This is first paragraph.</em>
   <p id="myid">This is second paragraph.</p>
</body>
</html>

To understand it in better way you can Try it yourself.

Useful Attribute Methods:

Following table lists down few useful methods which you can use to manipulate attributes and properties:

Methods Description
attr( properties ) Set a key/value object as properties to all matched elements.
attr( key, fn ) Set a single property to a computed value, on all matched elements.
removeAttr( name ) Remove an attribute from each of the matched elements.
hasClass( class ) Returns true if the specified class is present on at least one of the set of matched elements.
removeClass( class ) Removes all or the specified class(es) from the set of matched elements.
toggleClass( class ) Adds the specified class if it is not present, removes the specified class if it is present.
html( ) Get the html contents (innerHTML) of the first matched element.
html( val ) Set the html contents of every matched element.
text( ) Get the combined text contents of all matched elements.
text( val ) Set the text contents of all matched elements.
val( ) Get the input value of the first matched element.
val( val ) Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked.

Similar to above syntax and examples, following examples would give you understanding on using various attribute methods in different situation:

  • $(“#myID”).attr(“custom”) : This would return value of attribute custom for the first element matching with ID myID.
  • $(“img”).attr(“alt”, “Sample Image”): This sets the alt attribute of all the images to a new value “Sample Image”.
  • $(“input”).attr({ value: “”, title: “Please enter a value” }); : Sets the value of all <input> elements to the empty string, as well as sets the title to the string Please enter a value.
  • $(“a[href^=http://]”).attr(“target”,”_blank”): Selects all links with an href attribute starting with http:// and set its target attribute to _blank
  • $(“a”).removeAttr(“target”) : This would remove target attribute of all the links.
  • $(“form”).submit(function() {$(“:submit”,this).attr(“disabled”, “disabled”);}); : This would modify the disabled attribute to the value “disabled” while clicking Submit button.
  • $(“p:last”).hasClass(“selected”): This return true if last <p> tag has associated classselected.
  • $(“p”).text(): Returns string that contains the combined text contents of all matched <p> elements.
  • $(“p”).text(“<i>Hello World</i>”): This would set “<I>Hello World</I>” as text content of the matching <p> elements
  • $(“p”).html() : This returns the HTML content of the all matching paragraphs.
  • $(“div”).html(“Hello World”) : This would set the HTML content of all matching <div> to Hello World.
  • $(“input:checkbox:checked”).val() : Get the first value from a checked checkbox
  • $(“input:radio[name=bar]:checked”).val(): Get the first value from a set of radio buttons
  • $(“button”).val(“Hello”) : Sets the value attribute of every matched element <button>.
  • $(“input”).val(“on”) : This would check all the radio or check box button whose value is “on”.
  • $(“select”).val(“Orange”) : This would select Orange option in a dropdown box with options Orange, Mango and Banana.
  • $(“select”).val(“Orange”, “Mango”) : This would select Orange and Mango options in a dropdown box with options Orange, Mango and Banana.

 

jQuery – Selectors

The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM).

A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria.

The $() factory function:

All type of selectors available in jQuery, always start with the dollar sign and parentheses: $().

The factory function $() makes use of following three building blocks while selecting elements in a given document:

jQuery Description
Tag Name: Represents a tag name available in the DOM. For example $(‘p’)selects all paragraphs in the document.
Tag ID: Represents a tag available with the given ID in the DOM. For example$(‘#some-id’) selects the single element in the document that has an ID of some-id.
Tag Class: Represents a tag available with the given class in the DOM. For example $(‘.some-class’) selects all elements in the document that have a class of some-class.

All the above items can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking.

NOTE: The factory function $() is a synonym of jQuery() function. So in case you are using any other JavaScript library where $ sign is conflicting with some thing else then you can replace$ sign by jQuery name and you can use function jQuery() instead of $().

Example:

Following is a simple example which makes use of Tag Selector. This would select all the elements with a tag name p.

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   
   <script type="text/javascript" language="javascript">
   $(document).ready(function() {
      var pars = $("p");
      for( i=0; i<pars.length; i++ ){
         alert("Found paragraph: " + pars[i].innerHTML);
      }
   });
   </script>
</head>
<body>
   <div>
      <p class="myclass">This is a paragraph.</p>
      <p id="myid">This is second paragraph.</p>
      <p>This is third paragraph.</p>
   </div>
</body>
</html>

To understand it in better way you can Try it yourself.

How to use Selectors?

The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document.

Following table lists down few basic selectors and explains them with examples.

Selector Description
Name Selects all elements which match with the given elementName.
#ID Selects a single element which matches with the givenID
.Class Selects all elements which match with the given Class.
Universal (*) Selects all elements available in a DOM.
Multiple Elements E, F, G Selects the combined results of all the specified selectors E, F or G.

Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors:

  • $(‘*’): This selector selects all elements in the document.
  • $(“p > *”): This selector selects all elements that are children of a paragraph element.
  • $(“#specialID”): This selector function gets the element with id=”specialID”.
  • $(“.specialClass”): This selector gets all the elements that have the class ofspecialClass.
  • $(“li:not(.myclass)”): Selects all elements matched by <li> that do not have class=”myclass”.
  • $(“a#specialID.specialClass”): This selector matches links with an id of specialID and a class of specialClass.
  • $(“p a.specialClass”): This selector matches links with a class of specialClass declared within <p> elements.
  • $(“ul li:first”): This selector gets only the first <li> element of the <ul>.
  • $(“#container p”): Selects all elements matched by <p> that are descendants of an element that has an id of container.
  • $(“li > ul”): Selects all elements matched by <ul> that are children of an element matched by <li>
  • $(“strong + em”): Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>.
  • $(“p ~ ul”): Selects all elements matched by <ul> that follow a sibling element matched by <p>.
  • $(“code, em, strong”): Selects all elements matched by <code> or <em> or <strong>.
  • $(“p strong, .myclass”): Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class ofmyclass.
  • $(“:empty”): Selects all elements that have no children.
  • $(“p:empty”): Selects all elements matched by <p> that have no children.
  • $(“div[p]”): Selects all elements matched by <div> that contain an element matched by <p>.
  • $(“p[.myclass]”): Selects all elements matched by <p> that contain an element with a class of myclass.
  • $(“a[@rel]”): Selects all elements matched by <a> that have a rel attribute.
  • $(“input[@name=myname]”): Selects all elements matched by <input> that have a name value exactly equal to myname.
  • $(“input[@name^=myname]”): Selects all elements matched by <input> that have a name value beginning with myname.
  • $(“a[@rel$=self]”): Selects all elements matched by <a> that have rel attribute value ending with self
  • $(“a[@href*=domain.com]”): Selects all elements matched by <a> that have an href value containing domain.com.
  • $(“li:even”): Selects all elements matched by <li> that have an even index value.
  • $(“tr:odd”): Selects all elements matched by <tr> that have an odd index value.
  • $(“li:first”): Selects the first <li> element.
  • $(“li:last”): Selects the last <li> element.
  • $(“li:visible”): Selects all elements matched by <li> that are visible.
  • $(“li:hidden”): Selects all elements matched by <li> that are hidden.
  • $(“:radio”): Selects all radio buttons in the form.
  • $(“:checked”): Selects all checked boxex in the form.
  • $(“:input”): Selects only form elements (input, select, textarea, button).
  • $(“:text”): Selects only text elements (input[type=text]).
  • $(“li:eq(2)”): Selects the third <li> element
  • $(“li:eq(4)”): Selects the fifth <li> element
  • $(“li:lt(2)”): Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements.
  • $(“p:lt(3)”): selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements.
  • $(“li:gt(1)”): Selects all elements matched by <li> after the second one.
  • $(“p:gt(2)”): Selects all elements matched by <p> after the third one.
  • $(“div/p”): Selects all elements matched by <p> that are children of an element matched by <div>.
  • $(“div//code”): Selects all elements matched by <code>that are descendants of an element matched by <div>.
  • $(“//p//a”): Selects all elements matched by <a> that are descendants of an element matched by <p>
  • $(“li:first-child”): Selects all elements matched by <li> that are the first child of their parent.
  • $(“li:last-child”): Selects all elements matched by <li> that are the last child of their parent.
  • $(“:parent”): Selects all elements that are the parent of another element, including text.
  • $(“li:contains(second)”): Selects all elements matched by <li> that contain the text second.

You can use all the above selectors with any HTML/XML element in generic way. For example if selector $(“li:first”) works for <li> element then $(“p:first”) would also work for <p> element.