Friday, April 19, 2013

Selecting HTML elements with similar ID

You want to select only certain HTML elements that have id starting with some string? This is the right tutorial for you.
Look at first highlighted portion of code - it's jQuery selector that selects all elements starting with 'q'.
That means that only they will be transformed.

Here is the source:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
///////////////////////////////////////////////////////
    $('td[id^="q"]').each(function(index, value){
        $( this ).css( "color" , "red" );
        alert('index: '+index+' value of id attr.: '+value.id);
    });
////////////////////////////////////////////////////////
});
</script>
</head>
<body>
        <table class="data"  BORDER="1" CELLPADDING="2">
          <thead>
            <tr>
              <th>ID</th>
              <th>Name</th>
              <th>Occupation</th>
              <th>Approx. Location</th>
              <th>Price</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td id="qwe1">1</td>
              <td id="qwe2">Malkom</td>
              <td id="qwe3">Developer</td>
              <td id="asd1">Los Angeles</td>
              <td id="asd2">$39.95 / hour</td>
            </tr>          
          </tbody>
        </table>
</body>
</html>
Result is visible in Firebug:

No comments:

Post a Comment