Did you find this useful?
Socialize it today.


jQuery Basic Syntax

Saturday, June 09, 2012

Writing jQuery code is relatively easy, if you are already familiar with the Document Object Model (DOM), JavaScript, and CSS. You do not have to be an expert in any of those areas, to be proficient in jQuery. jQuery actually makes it easier for you to develop your web pages. Most of what you will initially do with jQuery is access elements within your page and apply the desired effects.


jQuery Syntax

jQuery syntax is simple to use and understand. We can easily select HTML elements and perform an action on the elements. The basic syntax is $(selector).action(). You start with a dollar sign($). The dollar sign is used to define the code as jQuery. Next define a selector to locate the target element(s). Finally, perform an action. Here are some examples on how to select elements.


$("div"); // selects all HTML div elements  
$("#myElement"); // selects one HTML element with ID "myElement"  
$(".myClass"); // selects HTML elements with class "myClass"  
$("div#myElement"); // selects div element with ID "myElement"  
$("ul li a.navigation"); // selects anchors with class "navigation"


Here is an example on how to place text within a div element:


<div id="test1"></div>
<script type="text/javascript">
    $(document).ready(function() {
        $("#test1").text("Hello, World!");
    });
</script>


Docment.Ready Function

It is a good practice to wait for the document to be fully loaded and ready, prior to allowing your jQuery code to be useable. One of the first things you should learn about jQuery is the ready event. Most of your jQuery code will be contained within this handler. This will ensure that the jQuery code does not run until the DOM is ready. It will confirm that any element being accessed is already loaded and accessible, so the script will not return any errors related to missing elements. In addition, it also ensures that your code is unobtrusive.


$(document).ready(function(){

   // jQuery code 

});

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

Professional jQuery HTML CSS and JavaScript Editor JavaScript and jQuery: The Missing Manual