JQuery Tutorial–II : Basic CSS Selectors

Selectors in JQuery is used to select specific document objects like <body>, <h1>, <p>, <a> and many more. It’s use has made writing JQuery very easier and get the required DOM to have control over it.

Using Basic CSS Selectors

Any DOM element may have their unique ID or group of selectors may have  a common class for styling. The ID selects unique element from the HTML DOM and class is applied for a wide selection. For eg.

For accessing these ids and classes of paragraph it can be done as :-

<script type="text/javascript">
  $('p#myParagraph').click(function(){
     alert('You clicked ID');
  });
  $('p.ourParagraph').click(function(){
     alert('You clicked Class');
  });
</script>

The p#myParagraph selects the paragraph with ID of myParagraph and p.myParagraph slects all the paragraph with class of ourParagraph.Each id value must be used only once within a document. If more than one element has been assigned the same id, queries that use that id will only select the first matched element in the DOM.

 

For applying styles to page elements, group of selection methods that work across all browsers can be applied. Those methods include selection by an element’s ID, CSS class name, tag name, and the DOM hierarchy of the page elements. Here are some examples to give you a quick refresher.

  • a – This selector matches all link (<a>) elements.
  • #specialID—This selector matches elements that have an id of specialID.
  • .specialClass—This selector matches elements that have the class of specialClass.
  • a#specialID.specialClass—This selector matches links with an id of specialID
    and a class of specialClass.

These basic selectors are powerful, but sometimes we need even finer-grained control over which elements we want to match. jQuery meets this challenge and steps up to the plate with even more advanced selectors.

SHARE JQuery Tutorial–II : Basic CSS Selectors

You may also like...

Leave a Reply

Your email address will not be published.

Share