Introduction


What is jQuery?


jQuery is a popular JavaScript library. The reasons that make jQuery so successful are:

  • Easy DOM manipulation
  • Easy selection
  • Cross-browser compatibility
  • Simplicity
  • Fast & small footprint

jQuery is defined as a function. The $ is just a pointer to the jQuery function. Therefore, $ is equivalent to jQuery:

// The following 2 statements are equivalent
$('#id').append(content);
jQuery('#id').append(content);

jQuery for DOM


jQuery exists because sometimes manipulating the DOM with JavaScript isn't easy:

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'>
    <title>Basic JQuery</title>
  </head>
  <body>
    <div id='javascript'>
    </div>
    <div id='jquery'>
    </div>
  </body>
</html>

The following scripts are included just before the closing body tag:

JavaScript

<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script>
  // Vanillia JavaScript
  var element = document.createElement('p');
  var content = document.createTextNode('Vanilla JavaScript DOM Manipulation');
  element.appendChild(content);
  var parent = document.getElementById('javascript');
  parent.appendChild(element);
  // jQuery
  $('#jquery').append('<p>jQuery DOM Manipulation</p>');
</script>

Result

Document Object Model


The Document Object Model (DOM) is a programming interface for HTML documents, an object-oriented representation of the web page itself. The DOM represents the document as nodes and objects thus allowing page modifications via a scripting language (DOM is language agnostic) such as JavaScript. Different browsers have different implementations of the DOM, however they all comply with certain web standards.

<body>
  <div>
    <div>
      <form>
        <input>
      </form>
      <ul>
        <li></li>
        <li></li>
      </ul>
    </div>
  </div>
</body>

The DOM representation of the document above resembles a tree-like structure:

body (root)
div
div
form, ul
input, li, li (leaves)

How to include jQuery


// Local
<script src='jquery-3.2.1.min.js'></script>

// Official
<script src='https://code.jquery.com/jquery-3.2.1.min.js'></script>

// CDN
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>

Note: If you use a CDN, your users' browsers will recognize that they already have a cached copy of jQuery from the same CDN when your site loads, which means that they don't need to download it again. So those extra KBs from jquery.min.js won't be downloaded and your site will load faster.

Ad1
advertisement
Ad2
advertisement
Ad3
advertisement
Ad4
advertisement
Ad5
advertisement
Ad6
advertisement