CSS selector & JQuery

CSS selector & JQuery

Selectors allows you to choose the element that you want to manipulate. CSS provide several way of selecting.

  • Universal selector: (*) select all elements.
  • Tag selector: p, a, span etc…
  • Id selector: this selector uses the following syntax “#” and id name (#id).
  • Class selector: the class selector is denoted by “.” followed by class name (.class)
  • More selectors : More

 

Applying css selectors in jquery:

  • Universal Selector : $(“*”)
  • Tag Selector:  $(“p”)
  • Id Selector: $(“#content”)
  • Class Selector:  $(“.text”)

 

Selecting Groups

If you need to format or apply the same behavior to several different element you can achieve this by grouping the elements h1, h2, h3, h4, h5, h6…

      $("h1, h2, h3, h4, h5, h6").css("text-decoration","underline");

 

Descendant Selectors:

Sometimes you will need to format or manipulate a particular tag that is inside one or more tags.  For example a <p> tag that is inside a <div> with id = warning (Div #warning  p). The format will  apply to all decendents of a tag.

     $("div#warning p").hide();

Note: Descendant selectors are read from right to left;

 

Child Selector:

This selector work similar to the descendant selectors but it has a little different.   It uses a symbol “>” and it’s just going to select the child that you specify.   Lets select a span inside a div (div > span).

<div >
  <span> Text</span>
  <p>Some</p>
</div>
$("div > span").css("color","blue");

 

Adjacent Sibling:

It selects the attribute that share the same parent. Adjacent use the “+” symbol.

<p>
  <div>
   <span>Inside div</span>
  </div>
  <span></span>
</p>
 $("div + span").html("<p>div is my parent</p>");

 

Attribute Selector:

With attribute selector you can select a tag that contains a particular property.  For example a link with rel = old  a[rel=old];

<a href="#"  rel="old" >click</a>
  $("a[rel=old]").click(function(){

      alert("you click me");
 });

 

Useful Links:

Jquery :  http://api.jquery.com/category/selectors/

Css Techniques : http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/

 

No Comments

Leave a comment