More On Selecting
In the last tutorial, we learned the basics of selecting elements with jQuery. Now, we will dive a bit deeper and write more code!
Code Demo
To explain the concepts in this tutorial, we will write some example code. The code will be as follows:
$(document).ready(function(){
$("p").click(function(){
$(this).text("A p tag")
});
$("#p").click(function(){
$(this).text("A p id")
});
$(".p").click(function(){
$(this).text("A p class")
});
});
And then, add the following couple of lines into your index.html
file:
<p>hi</p>
<div id="p">hi</div>
<div class="p">hi</div>
Code Result
After running your code and opening the HTML page, you'll notice something similar to what we had in the previous tutorial, but if you click on a line of text, it will change to something depending on what it is (a p
tag, a div
tag with and id of p
, or a div
tag with a class of p
). So, now, let's uncover the mysteries behind this example!
What Goes In The $
Function
In the previous examples, we had a couple of strings that we passed into the $
function.
The first one was "p"
, and if you're familiar with CSS selectors, then you'd know that just a p
means a p tag.
We also had "#p"
, and with CSS selectors, it means something with an id of p
(represented by the hashtag). So, this would "influence" or div
with the p
tag.
And finally, we had ".p"
, which is anything with a class of p
, denoted by the period. So, this affects our div
with the class of p
.
Other Selectors
We already learned that jQuery selectors are the same as CSS selectors. Here are a few more examples:
ul li.hello
: selects all list items within an unordered list that have a class ofhello
#code
: selects all elements with an id ofcode
.navbar
: selects all elements with a class ofnavbar
a
: selects all links (tag ofa
)[href]
: selects all elements with an attribute ofhref
ul li:first-child
: selects the first element of every unordered list*
: selects all elementsp:first
: selects the first<p>
taga[target='_blank']
: selects all links with the attributetarget
set to_blank
a[target!='_blank']
: selects all links with the attributetarget
NOT set to_blank