Getting started with jquery

Create a file hello.html with the following content:

<!DOCTYPE html>
      <title>Hello, World!</title>
         <p id="hello">Some random text</p>
      <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <script>
         $(document).ready(function() {
             $('#hello').text('Hello, World!');

Open this file in a web browser. As a result you will see a page with the text: HelloWorld!

Explanation of code

  1. 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.

  2. 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() { ... }); 

  3. 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:

    1. 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.

    2. Set the text() inside the selected element to HelloWorld!.

      #     ↓ Pass a `selector` to `$jQueryreturns our element
      $('#hello').text('Hello, World!');
      #                              ↑ Set the Text on the element