Google

Jul 2, 2013

CSS Selectors Tutorial with FireBug

This tutorial extends the JavaScript tutorial with FireBug. The purpose of this tutorial is to debug CSS selectors in FireBug. CSS selectors are used in selecting your DOM element for debugging and for writing automated tests to verify the displayed DOM elements.




Step 1: Here is a basic HTML document (cssselectortest.html) to apply the CSS selectors.

 
<html lang="en" >
<head>
    
    <title>test app</title>
 
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js?ver=1.9.1"></script>                                                                
 </head>            
 
   
<body>
  <div id="myApp">
        <h2 class="myClass">CSS selector test</h2> 
        <h2 class="myClass">CSS selector test2</h2>   
     <h2 class="myClass">CSS selector test3</h2>  
  </div>
</body>



Step 2: Open Firefox browser and type the URL to the above HTML (i.e. cssselectortest.html) file. Make sure that you have the FireBug add on installed. If not, download it and drag and drop on to the Firefox.



On the RHS bottom console, you have CSS selector as shown below.

 
console.clear();
console.log( jQuery('div#myApp h2.myClass:eq(-1)') );

The above CSS selector, selects the last  h2 tag  with class "myClass" under a DIV tag with id "myApp". You can experiment with other CSS selectors and see what is selected on LHS window, and once you highlight the selection on the bottom LHS window, you can see the HTML page highlighted as shown below.


You can try the following selectors to see what is highlighted.
 
console.log( jQuery('div#myApp h2.myClass:eq(0)') );//First h2
console.log( jQuery('div#myApp h2.myClass:eq(1)') );//2nd h2
console.log( jQuery('div#myApp h2.myClass:eq(2)') );//Third h2


For the following HTML

 
<html lang="en" >
<head>
    
    <title>test app</title>
 
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js?ver=1.9.1"></script>                                                                
 </head>            
 
   
<body>
  <div id="myApp">
        <h2 class="myClass">CSS selector test</h2> 
        <h2 class="myClass">CSS selector test2</h2>   
     <h2 class="myClass">CSS selector test3</h2>  
  </div>
  <h2>Test +</h2>
</body>

Try the following selectors

 
console.clear();//clear the console
console.log( jQuery('div#myApp h2'));//All h2 elements inside the div element with id "myApp"
console.log( jQuery('div#myApp>h2'));//All h2 elements where the parent is a div with id "myApp"
console.log( jQuery('div#myApp, h2'));//All div elements with id "myApp" and h2 elements
console.log( jQuery('div#myApp+h2'));//All h2 elements that are immediately followed by div element with id "myApp"


Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home