Testing jQuery with JavaScript
Testing JavaScript Framework Library - jQuery
Including jQuery
To test a JavaScript library, you need to include it in your web page.
To include a library, use the <script>
tag with the src
attribute set to the library's URL:
Including jQuery
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
</body>
</html>
jQuery Description
The main jQuery function is the $()
function (jQuery function). If you pass a DOM object to this function, it returns a jQuery object with jQuery functionalities added to it.
jQuery allows you to select elements using CSS selectors.
In JavaScript, you can assign a function to handle the window load event:
JavaScript Way:
function myFunction() {
var obj = document.getElementById("h01");
obj.innerHTML = "Hello jQuery";
}
onload = myFunction;
The equivalent in jQuery is different:
jQuery Way:
function myFunction() {
$("#h01").html("Hello jQuery");
}
$(document).ready(myFunction);
In the last line of the above code, the HTML DOM document object is passed to jQuery: $(document)
.
When you pass a DOM object to jQuery, jQuery returns a jQuery object wrapped around the HTML DOM object.
The jQuery function returns a new jQuery object, where ready()
is a method.
Since functions are variables in JavaScript, you can pass myFunction
as a variable to jQuery's ready
method.
| | jQuery returns a jQuery object, different from the passed DOM object. <br>The jQuery object has different properties and methods than the DOM object. <br>You cannot use HTML DOM properties and methods on a jQuery object. | | --- | --- |
Testing jQuery
Try the following example:
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/1.8.3/jquery.min.js"></script>
<script>
function myFunction() {
$("#h01").html("Hello jQuery")
}
$(document).ready(myFunction);
</script>
</head>
<body>
<h1 id="h01"></h1>
</body>
</html>
Try this example as well:
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/1.8.3/jquery.min.js"></script>
<script>
function myFunction() {
$("#h01").attr("style", "color:red").html("Hello jQuery")
}
$(document).ready(myFunction);
</script>
</head>
<body>
<h1 id="h01"></h1>
</body>
</html>
As you can see in the examples above, jQuery allows chaining (chain syntax).
Chaining is a convenient way to perform multiple tasks on the same object.
Want to learn more? tutorialpro.org provides excellent jQuery Tutorials.