Selecting Elements with jQuery
This YouTube video was created by Steve Griffith.
The jQuery()
function is the foundational function of the jQuery library is the fundamental way of selecting and interacting with elements on the page. The basic syntax would look something like this.
$(selector).action()
The $
serves as a shortcut for the jQuery()
function. The selector
is the query, using CSS Selector syntax, to find HTML elements. Finally, the action()
is the jQuery action to be performed on the elements.
Now, let see this jQuery()
function in action. Assuming the following HTML:
<main>
<p class="first">Lorem ipsum dolor sit</p>
<p class="second">Lorem ipsum dolor sit</p>
<p class="third">Lorem ipsum dolor sit</p>
</main>
If we wanted to change the font color of the first paragraph, it could be done like so:
// jQuery
$('.first').css('color', 'red')
// Vanilla JavaScript
document.querySelector('.first').style.color = 'red'
Now, if we wanted select and manipulate multiple elements, for example, changing font family for all of the paragraph tags, that can be accomplished, like this:
// jQuery
$('main p').css('font-family', 'arial')
// Vanilla JavaScript
document.querySelectorAll('main p').forEach(p => p.style.fontFamily = 'arial')