To use jQuery Methods
, you have to insert it into the <head>
element. It can either be downloaded and stored on the
site from here (choose the uncompressed version), or you can link to it using a cdn
from here. This is what we are using here.
Let's see how jQuery
works:
Selecting using jQuery
:
$
$(document).ready(function(){
$("a");
$("div");
$(".class")
$(".page-name")
$(".container")
$("#id")
$("#menu1")
- $("[attribute]")
$("[src]")
$("[href]")
$("element>element")
$("article>p")
$(article p")
$("p:first")
$("p:last")
$(":header")
The jQuery selector
});
Stops jQuery from loading until the document itself has loaded
Selects all anchor elements
Selects all DIV elements
...
The class selector:
...
The Id selector:
...
The attribute selector
The direct descendant selector
Return all <p>
elements that are direct descendants of the <article>
element.
<article>
<p>
Return all <p>
elements that are descendants (ie children and everything below) of the <article>
element.
<article>
<h2>
<p>
The first instance of the <p>
element (a pseudo selector)
The last instance of the <p>
element (a pseudo selector)
All the header elements from <h1>
to <h6>
(a pseudo selector)
Selecting CSS from jQuery
$("div").css("background-color");
$("p").css("font-family");
$(".footer-section").html();
Returns the background color of <div>
elements
Returns the font style of <p>
elements
...
Returns all the HTML
from the class footer-section
Manipulating using jQuery
:
$("div").css("background-color", "red");
$("ul").css("border", "solid, 1px, black");
$("h1").html("Hello World!");
$(".website-links").html("<h3>Hello World</h3>");
$(".website-links p").text("Hello World!");
$("h6").append("<span> © 2020</span>")
$("p").remove();
$(".main-body h2").empty();
let green = $("code").css("color");
Colors the backgound of DIVs red.
Surrounds every <ul>
element with a solid, 1px wide balck border
Replaces the h1 title (jQuery
) with Hello World!
Replaces what is in the website-links
class with an <h3>
element containing Hello World!
Replaces the text within the descendant <p>
element in the .website-links
with Hello World!
Appends © 2020 to the <h6>
element
Removes all <)>
elements
Empties all <h2>
elements of their contents
$("p").css("color", green);
We assign the variable green to be the color in the CSS assigned to <code>
elements. (The
actual color is this color
, but we have called it "green".) Now, we use jQuery
to target all
<p>
elements and change their color to our new definition, green. Note that we have not used ""
,
as this is a variable.
You will of course notice that we have inversed the colors of this page. The buttons and links are pink, while the code sections, menu and
footer are blue. This has all been done with jQuery
. Should you want to, you can see the script here.