Create a file hello.html
with the following content:
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<div>
<p id="hello">Some random text</p>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(document).ready(function() {
$('#hello').text('Hello, World!');
});
</script>
</body>
</html>
Open this file in a web browser. As a result you will see a page with the text: Hello, World!
Loads the jQuery library from the jQuery CDN:
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
This introduces the $
global variable, an alias for the jQuery
function and namespace.
Be aware that one of the most common mistakes made when including jQuery is failing to load the library BEFORE any other scripts or libraries that may depend on or make use of it.
Defers a function to be executed when the DOM (Document Object Model) is detected to be "ready" by jQuery:
// When the `document` is `ready`, execute this function `...`
$(document).ready(function() { ... });
// A commonly used shorthand version (behaves the same as the above)
$(function() { ... });
Once the DOM is ready, jQuery executes the callback function shown above. Inside of our function, there is only one call which does 2 main things:
Gets the element with the id
attribute equal to hello
(our selector #hello
). Using a selector as the passed argument is the core of jQuery's functionality and naming; the entire library essentially evolved from extending document.querySelectorAllMDN.
Set the text()
inside the selected element to Hello, World!
.
# ↓ - Pass a `selector` to `$` jQuery, returns our element
$('#hello').text('Hello, World!');
# ↑ - Set the Text on the element
For more refer to the jQuery - Documentation page.