jQuery selectors code snippets demo

Selector is the most basic things in jQuery. Their use is very simple and straight and correct use of selectors can enhance the efficiency of writing jQuery code. I have put together some of the common selectors which are pretty common.

ID Selector
$(document).ready(function () {
   $('#dvDummy').css('background', '#000000');
});
Class Selector
$(document).ready(function () {
   $('.class1').css('background', '#000000');
});
Element Selector
$(document).ready(function () {
   $('p').css('font-size', '14px');
});
Selector (loop through all elements)
$(document).ready(function () {
   $('form *').css('color', '#FFFF00');
});
Select Multiple Elements
$(document).ready(function () {
   $('p, div').css('margin', '0');
});
The parent > child (immediate child element)
$(document).ready(function () {
   $('div > span').css('color', '#FF0000');
});
:first and :last (take the first element or the last element)
$(document).ready(function () {
   $('span:first').css('color', '#FFFF00');
   $('span:last').css('color', '#FFFF00');
});
:even and :odd (Select elements with an even index or odd index elements. The index starts from 0.)
$(document).ready(function () {
   $('tr:even').css('color', '#00FF00');
   $('tr:odd').css('color', '#0000FF');
});
:eq(x) (Selects element with the specified index)
$(document).ready(function () {
  $('tr:eq(2)').css('background', '#FFFF00');
});
:contains(text) (Select element which contains specified text)
$(document).ready(function () {
  $('div:contains("jQuery")').css('color', '#FFFF00');
});
:hidden (Selects hidden elements)
$(document).ready(function() {
  $('div:hidden').show(500);
});
:visible (Selects visible elements)
$(document).ready(function() {
  $('div:visible').css('color', '#FFFF00');
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..