jQuery: Selecting and Modifying
Selection
jQuery is an extremely popular Javascript library. It helps to speed up common tasks if you don’t mind adding a script that is 9000 lines long to your project. This post will cover the very basic methods that jQuery uses to select and modify elements.
To begin, you select elements with jQuery with the $ symbol:
$()
This is simply referring to a function in the jQuery library. To select elements with vanilla Javascript see my post Javascript DOM Manipulation. jQuery $()
uses CSS style selectors and behaves very similarly to querySelectorAll()
. Here are some examples of selections:
// to select all paragraph tags
$("p")
// to select a class called header
$(".header")
// to select an element with ID intro
$("#intro")
// to select all a tags inside of li's
$("li a")
:nth-of-type(n)
How to select a specific number n in a list. Given this:
<h1>This is the first H1 on this Doc</h1>
<p>This is a paragraph describing the contents on this page</p>
<ul>
<li>Dog</li>
<li>Cat</li>
<li>Parrot</li>
</ul>
<ol>
<li>First</li>
<li>2nd</li>
<li>3rd</li>
<li>4th</li>
</ol>
We can see that if we select all li‘s and ask for the first it will give us the first li in each list, whether the list is ordered or not. If we want to select just the first li in the unordered list we have to specify that.
Manipulation
Then to apply a style to the selected object you use the following jQuery method:
.css(property, value)
To modify elements with vanilla Javascript see my post Javascript DOM Manipulation.
Here is a quick example of the .css method:
// we will select a specific span of text with ID header and give it a font size of 2em
$("#header").css("font-size", "2em")
We can also pass in an object for the styles:
var headerStyle = {
backgroundColor: "black",
fontColor: "red",
border: "3px solid blue"
}
$("#header").css(headerStyle);
// note that we do not need "" parentheses when passing in the headerStyle object
Note that we use camelCase for our CSS selectors in jQuery.
Here are some more quick examples:
Comments
Recent Work
Basalt
basalt.softwareFree desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.
BidBear
bidbear.ioBidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.