jQuery ready state for DOM

Today I was trying out jQuery and trying to addClass to a p tag. I was doing it at the top of the page i.e.

{code type=’codetype’}

<head>

<script src=”jqeury.js”>

$(“p”).addClass(“selected”)

</script>

</head>

<body>

<p>Hello</p>

</body>

{/code}

This will not work because the p tag is below the jQuery code. jQuery looks for the p tag above the lines it was written in.

To overcome this problem, you can either write the above script withing  $(docment).ready(function() {}) function or write the jQuery script after the p tag was written.

i.e.

{code type=’codetype’}

<head>

<script src=”jqeury.js”>

$(document).ready(function(){

$(“p”).addClass(“selected”);

};

</script>

</head>

<body>

<p>Hello</p>

</body>

{/code}

or

{code type=’codetype’}

<head></head>

<body>

<p>Hello</p>

<script src=”jqeury.js”>

$(“p”).addClass(“selected”)

</script>

</body>

{/code}

When using the ready() function the jQuery statement is executed after the DOM has loaded completely thus allowing the p tag below the code to be found.