JQuery Notes
JQuery is a JavaScript library that makes JavaScript more succinct and easier to manage. This page will compare how multiple things written in JavaScript can be written in JQuery.
Including JQuery
To incorporate JQuery into your project, you can add a CDN to your project. Unlike most script tags, this CDN will be put in the head tags.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>The ready() Method
All JQuery should be written inside the method below. This function waits until the webpage has loaded before running any code.
$(document).ready(function(){
//code
});Selection
JQuery makes selection shorter by condensing the function of the querySelectorAll method into one symbol: $
Remember: the querySelectorAll method creates a list of HTML elements. Don't forget to use an index to select a specific item.
Javascript:
document.querySelectorAll('h1')[0];JQuery:
$('h1')[0];Changing CSS
The css() method is a quick and direct way to set CSS properties. It is often easier to use the css method rather than the setAttribute method or by changing the style property as the property names used in the css method match that of regular CSS, where the properties used in the setAttribute method and style property can be a little different (see example below):
Javascript:
var myElement = document.querySelectorAll('h3')[0];
myElement.setAttribute('backgroundColor', 'red');JQuery:
var myElement = $('h3')[0];
myElement.css('background-color', 'red');Text
The text() method can be used to both return the text within all selected HTML elements, as well as change it.
Changing Text
JavaScript:
var elem = document.querySelectorAll('div')[0];
elem.innerText = "Hello World";JQuery:
$('div').text("Hello World");
Returning Text
console.log($('div').text()); //Retrieve the text and print it to the consoleHTML
The html() method works similarly to the text method, except that it returns all of the html within an element, not just the text.
Changing Text
JavaScript:
var elem = document.querySelectorAll('div')[0];
elem.innerHTML = "<h1>Hello World</h1>";JQuery:
$('div')[0].html("<h1>Hello World</h1>");
Returning Text
console.log($('div').html()); //Retrieve the text and print it to the consoleEvents
Instead of using the addEventListener method, JQuery has some easier ways to handle event listeners.
JavaScript:
var elem = document.querySelectorAll('div')[0];
elem.addEventListener("click", function() {
document.getElementById("demo").innerHTML = "Hello World";
});JQuery:
$('div')[0].click(function() {
$(this).text("Hello World");
});Multiple Events
If you want to apply multiple events to an element using JQuery, you can use the on() method as shown below.
$("h1").on({
mouseenter: function(){
$(this).css("font-size", "3em");
},
mouseleave: function(){
$(this).css("font-size", "2em");
},
});