jQuery is the most popular JavaScript library, which provides useful set of features for DOM and Ajax related functionalities. Statistics from http://trends.builtwith.com/javascript/JQuery, explains how popular jQuery is.
The above diagram shows that ~34.21% of sites that use JavaScript are using jQuery. In this post, we will start learning jQuery with some basic usage.
Let us start with document.getElementById equivalent in jQuery. We can use the CSS selectors to select the DOM elements using jQuery. Suppose if we have an element with id “element1“, then in order to get the DOM object of the element, in core JavaScript we will use
document.getElementById( "element1" )
Using jQuery, we can select the above element using the below statement:
$( '#element1' )
In the above statement, # represents that element1 is the ID. In the same way, we will use “.” to select elements by class name. Suppose in our HTML document, we have few div, span and form elements whose has class “sample-class“. To select all the elements with class name “sample-class“, we can use
document.getElementsByClassName( "sample-class" )
The above method is not supported in Internet Explorer. So, in Internet Explorer, we have to write our own method to get the elements with a particular class.
Using jQuery, we can get the elements with “sample-class” class using
$( '.sample-class' )
The above method works in all major browsers (IE, Firefox, Opera, Safari). So, another advantage of using jQuery is, it works in all major browsers.
Suppose that in a document some div and span elements have the class “sample-class“. If we need to get all the “div” elements with class “simple-class”, just use:
$( 'div.sample-class' )
and
$( 'div' )
returns all the div elements in the documents. To get all div elements, which has class attribute, use:
$( 'div[class]' )
To get all the div elements, which has name attribute and attribute’s value is “SampleDIV”, use:
$( 'div[name=SampleDiv]' )
You can get more information about attributes from http://docs.jquery.com/Attributes.
Loading...