Tuesday, March 6, 2012

Basic jQuery selectors


 jQuery is a simple but really powerful JavaScript library. jQuery contains tons of features but my favorite is selectors. jQuery provides amazing set of selectors which makes anything / everything a lot simple.
So let's start with jQuery selectors.

jQuery Selector 1: Select all elements
$('*').val('I am a HTML element');
This will select all HTMl elements


jQuery Selector 2: Select specific HTML elements
$('input').val('I am a input element');
This selector will select all input elements. Instead of input you can use div, span, label or any other HTML element.

jQuery Selector 3: Select by id
$('#fooId').val('my id is fooId');
It will select element which have id='fooId'.'#' is used to specify id in selector.

jQuery Selector 4: Select by class
$('.fooClass').val('I have fooClass');
This will select all elements which have class='fooClass'. '.' is used to specify class in selectors.
If you want to select only input element you can use.
$('input .fooClass').val('I am a input element with fooClass');

jQuery selector 5: Select by attribute
$("input [name='fooName']").val('I am a input with name=fooName');
This will select all input elements which have name=fooName. Instead of name you can also use other attributes in selector.


jQuery selector 6: Select nth element
$('input :eq(2)').val('I am the 3rd input');
It will select 3rd input element. The index passed to eq(n) is zero based.

Here is a jsFiddle which contains all selectors we discussed till now



You can get complete list of selectors from here.

~Ajinkya.

No comments:

Post a Comment