Search code examples
javascriptjqueryhtmllogicconcept

What is the difference between these two jQuery usage


Im a jquery starter so if its a wrong one forgive me :)

I just want to know why placing the content at different positions made this script working, although to my best i think script to kept in head section of the document. Please explain the concept.

Working Code

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example 2</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

</head>

<body>

<p>
</p>

<script type="text/javascript">
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
</script>

</body>
</html>

Not Working

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example 2</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
</script>
</head>

<body>

<p>
</p>

</body>
</html>

Solution

  • In the second instance the code is executed before the <p> has been parsed into the DOM tree, so while it still works there's nowhere to put the output text into. In other words, jQuery("p") matches no element so .html() "does nothing".

    You can fix this by either waiting for the DOM to be fully parsed:

    jQuery(function() {
        jQuery("p").html(...);
    });
    

    or by using an output mechanism that does not depend on the <p> existing, such as alert() or console.log().