jQuery is a powerful, widely used library that makes a lot of common practices in javascript web development a bit easier. Here are some examples of how you can use jQuery for some common things we've already done:
Vanilla JS | jQuery | |
---|---|---|
AJAX |
|
|
Get element | var span = document.querySelector('span'); |
var $span = $("span"); |
Create element | var a = document.createElement("a"); |
var $a = $("<a>"); |
Add child | span.appendChild(a); |
$span.append($a); |
Get textContent | var linkText = a.textContent; |
var $linkText = $a.text(); |
Set textContent | a.textContent = "new text content"; |
$a.text("new text content"); |
Get attribute | var href = a.getAttribute("href"); |
var $href = $a.attr("href"); |
Set attribute | a.setAttribute("href", "http://wikipedia.org/"); |
$a.attr("href", "http://wikipedia.org/"); |
Add event listener | a.addEventListener("click", function() { ... }; |
$a.on("click", function() { ... }); |
The easiest way to add jQuery to your page is by adding the following script tag to your HTML (put this tag before your own scripts):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
The most important difference with using jQuery for DOM manipulation is that
jQuery always works with a "set" of elements. Before, you would do document.querySelector("li.todo")
and that would just return ONE element. But when you do the equivalent with
jQuery ($("li.todo")
), you get a set of elements that match that
selector. Furthermore, the DOM manipulation operations (like setting text content
or changing an attribute or adding a class, etc.) are available on the set.
In other words, jQuery makes it easy to manipulate more than one element at a
time, which is usually helpful. Here's an example:
// Get all the todo list items on the page
var $listItems = $("li.todo");
// Add a class to them all
$listItems.addClass("complete");
Before, you would have to use document.querySelectorAll()
and
a for
loop. But jQuery makes it easy.
Taking it one step further, jQuery also allows you to chain these operations together. This allows your code to be a bit more succinct.
$("<li>").text("...").addClass("...").appendTo("ul")