jQuery code is often wrapped in jQuery(function($) { ... });
so that it only runs after the DOM has finished loading.
<script type="text/javascript">
jQuery(function($) {
// this will set the div's text to "Hello".
$("#myDiv").text("Hello");
});
</script>
<div id="myDiv">Text</div>
This is important because jQuery (and JavaScript generally) cannot select a DOM element that has not been rendered to the page.
<script type="text/javascript">
// no element with id="myDiv" exists at this point, so $("#myDiv") is an
// empty selection, and this will have no effect
$("#myDiv").text("Hello");
</script>
<div id="myDiv">Text</div>
Note that you can alias the jQuery namespace by passing a custom handler into the .ready()
method. This is useful for cases when another JS library is using the same shortened $
alias as jQuery, which create a conflict.
To avoid this conflict, you must call $.noConflict();
- This forcing you to use only the default jQuery namespace (Instead of the short $
alias).
By passing a custom handler to the .ready()
handler, you will be able to choose the alias name to use jQuery.
$.noConflict();
jQuery( document ).ready(function( $ ) {
// Here we can use '$' as jQuery alias without it conflicting with other
// libraries that use the same namespace
$('body').append('<div>Hello</div>')
});
jQuery( document ).ready(function( jq ) {
// Here we use a custom jQuery alias 'jq'
jq('body').append('<div>Hello</div>')
});
Rather than simply putting your jQuery code at the bottom of the page, using the $(document).ready
function ensures that all HTML elements have been rendered and the entire Document Object Model (DOM) is ready for JavaScript code to execute.