jQuery : Referring to an element in HTML page

While last post was about referring to an element in through only javascript. Here we will see how to access the same element with the popular javascript library, jQuery.
This is a tutorial straight from the jQuery site itself.
Lets start from the beginning as to add this library to our page. The code will look something like below, depending upon where you have placed your jQuery.js file.


Now lets see the old code of ours when we are doing an alert at the document load complete. The HTML file will look as



  


    
    
   
    
  
  
    Hello World
Hello, this is first div.

Now the point here is to see that we removed the following from the HTML,


That means, HTML code will be pure content. There would be no functional elements inside HTML document. This helps maintain the documents for everyone. Now the code to do the same alert on document load will look as

 $(document).ready(function(){
   // Your code here
   alert("Page is loaded");
 });

Thats simple, but to keep in mind that jQuery gives a “$” to us. Everything we do with jQuery will start with a “$”. Though there are methods to override this, but basic will be using a “$”. And now the whole file will look as



  


    
    
   
    
  
  
    Hello World
Hello, this is first div.

Next, jQuery allows a short hand of the same thing (action on document loading) and we can write that as below

$(function() {
 // Handler for .ready() called.
 alert("Page is loaded");
});

The reference to this is on the jQuery website itself. Now lets see how we can access an element in the HTML document, and jQuery makes it simple as

$("#firstDiv")

The above code is to select our first div on the HTML page.
And for the classes, jQuery allows us to do as below

$(".myClass")

This later thing will select all the elements which are given a CSS class named “.myClass”
These kind of things are called CSS Selectors of jQuery. Now you can understand the codes we have written before, which include a “$”.
Hope that helps someone.