JQuery Selectors - Basic 1

by limd

HTML

<div>
    <li><a href="http://api.jquery.com/category/selectors/">Selectors Documentation</a></li>
    <li><a href="http://codylindley.com/jqueryselectors/">Selectors Examples</a></li>        
</div>

<div>    
    This is a div    
    <br />
    <span id="mySpan">red text</span>
    <span>this is a span within a div</span>
</div>
<span>this is a span NOT within a div</span>
<div>This is another div</div>

<fieldset class="myRedCSSClass">
    <table>
        <tr>
            <td class="myBlueCSSClass"> 1 </td>
            <td> 2 </td>
        </tr>
    </table>
</fieldset>

CSS

div {margin: 0.5em}
fieldset {margin: 0.5em}
table{width: 20em;}

.red {color: Red;}
.blue {color: Blue;}

.myRedCSSClass {background-color: Red}
.myBlueCSSClass {background-color: Blue}

JavaScript

// ----------------------------------------------------------------------------
/* TAG SELECTORS */
// ---------------------------------------------------------------------------
$(document).ready(function(){    
    
    // select all div tags - change css class on all of them
    $('div').addClass('blue');
    
    // select all div tags - apply function against all of them
    $('div').each(function(){
        //alert($(this).html());
    });
       
    // select all div and table tags - apply css attribute to all of them
    $('div, table').css('border','1px solid #000000');
    
    // select all span tags within a div - apply css attribute to all of them
    $('div span').css('background-color','#ededed');
    
    // ----------------------------------------------------------------------------
         /* ID SELECTORS */
    // ----------------------------------------------------------------------------    
    
    // select a specific id - change css class
    $('#mySpan').addClass('red');
    
    // ----------------------------------------------------------------------------
         /* CSS SELECTORS */
    // ----------------------------------------------------------------------------    
    
    // select all tags that have particular css class
    $('.myRedCSSClass').removeClass('myRedCSSClass').addClass('red');
    
    // select all table cell tags that have particular css class
    $('td.myBlueCSSClass').removeClass('myBlueCSSClass');
    
});