Setting Up JQuery and Basic DOM Manipulation

Page last updated on 2011 / 25 / 07

Installation of JQuery is quite simple really, or easy to assume that it is when you've been developing sites for a while...

Include the following within the <head> section of your HTML:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
 

The above snippet is the full basic framework of JQuery, all styling and plugins require their separate files for added functionality. Because this script is referencing a file on Google's server, there's a fair chance that the user (including you) already have this file cached on the client-side, meaning that minimal bandwidth is used. This is the advantage of having a CDN (Content Delivery Network) style of JQuery.

Consider the following example. I have provided the HTML and a working example below it. This will show you some basic DOM manipulation, courtesy of JQuery.

  1. <html>
  2. <head>
  3. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
  4. <script type="text/javascript">
  5.  
  6. function change_color() {
  7. randomhexcode = Math.round(0xffffff * Math.random()).toString(16);
  8. $('#testid').css('background-color','#' + randomhexcode);
  9. }
  10.  
  11. function class_contents() {
  12. alert($('.testclass').html());
  13. }
  14.  
  15. function id_contents() {
  16. alert($('#testid').html());
  17. }
  18.  
  19. function id_contents() {
  20. alert($('#testid').html());
  21. }
  22.  
  23. function random_from_list() {
  24. randomnum = Math.floor(Math.random()*($('ul > li').length+1)); // Pick a random number between 0 and the # of <li> tags on the page
  25. alert('#'+randomnum+' of '+$('ul > li').length+' <li> tags says "' +$('ul > li:eq('+(randomnum-1)+')').html()+ '"');
  26. }
  27.  
  28. $(document).ready(function()
  29. {
  30. $("a").css('cursor','pointer');
  31. $("a").attr('href','#');
  32. });
  33.  
  34. </script>
  35. </head>
  36. <body>
  37.  
  38. <div id="testid" class="testclass">This is my text</div>
  39. <ul>
  40. <li>This</li>
  41. <li>is</li>
  42. <li>an</li>
  43. <li>unordered</li>
  44. <li>list</li>
  45. </ul>
  46.  
  47. <a onclick="class_contents()">Show Contents By Class</a> :
  48. <a onclick="id_contents()">Show Contents By ID</a> :
  49. <a onclick="change_color()">Change Color</a> :
  50. <a onclick="random_from_list()">List</a>
  51.  
  52. </body>
  53. </html>

Working Example

This is my text
  • This
  • is
  • an
  • unordered
  • list
Show Contents By Class : Show Contents By ID : Change Color : List

Previous Article
An Introduction to JQuery: The Monolithic JS Library




Tweet