In this second segment in my jQuery series, we will review getting objects by ID Selector (#id), by Class Selector (.class), by Tag, and by Attribute (.attr()).
In the first part, “How to get started with jQuery,” I set up the foundation code for our HTML file index.html and our styles with the styles.css file. Then we invoked our first “ready()” event function, adding in a click event handler alert.
The files you’ll need to follow along in this tutorial, including html, css, script, and images, are available for download here in a zip file.
Get Object by jQuery ID Selector (#id)
Getting an object by id is utilized to search specified by the id attribute of an element. Each id value must be used only once within a single web document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on; however, a document with more than one element using the same ID becomes invalid.
In the index.html file, we will add in the following <input> line of code just below the “Switch” paragraph as shown below:
<p><strong>Switch</strong></p>
<input type="button" id="switch-two" value="Switch" />
By definition, the jQuery toggleClass() method is utilized to toggle between adding and removing one or more classes for the selected elements. This method checks each element for the specified classes. The classes are added if missing, and removed if already set — this creates a toggle effect. However, by using the “switch” parameter, you can specify only to remove or only to add a class.
In this demonstration, we will apply one class with the toggleClass() method to the second article with id=”two” which, when clicked, will render it from a 2px blue border to a 2px green border, and it will also change the height from 200px to 100px. We will add the following jQuery to our ready() event just below the first click function call we added in the first segment:
$('#switch-two').click(function () {
$('#two').toggleClass('newClass');
});
Open your index.html file in your browser, then click on the Switch button and you will see the transformation as displayed in Chrome 17.0.9 in Figures A and B below:
Figure A
Figure B
When you click the Switch button, it triggers the toggle function which finds the element by id replacing the id with “newClass”, which defines the shadow box article as 110px high and the border color set to green. Clicking on the Switch button again resets the id to the original.
Get Object by Class (.class)
In this demonstration, we will modify multiple objects from one get call by grabbing all objects of a certain class — in this case, the class=”test”. In our index.html file we will add in the following lines of code just below the previous paragraph, creating a new input button named “Test Button”.
<p><strong>Test Button</strong></p>
<input type="button" id="test-switch" value="Test Button" />
Then, in our <script> area, add in the following lines of JavaScript just below the previous code that we added inside our ready function, and save the file:
$('#test-switch').click(function () {
$('.test').toggleClass('newTestClass');
});
Now, in our styles.css file add in the following lines and save the file:
#content .newTestClass {
width: 300px;
height: 100px;
border: 2px solid #0FF;
}
Refresh the index.html document in your browser, and click on the Test Button input; the get object by class is activated, and the result is shown in Figure C as displayed in Chrome 17.0.9:
Figure C
In this example, we used jQuery to find the element with the id of test-switch
(the Test Button), and when we clicked on the button, jQuery triggered a function to toggle the class (“newTestClass"
) on the two elements (the second article
and the section
) with a class of test
.
Get Objects by Tag
To get an object by tag you just need to pass the name for the particular tag you are looking for to the ready function. In this example, let’s add these lines of code to our index.html file and save the file:
<p><strong>Article Button</strong></p>
<input type="button" id="article-switch" value="Article Tag Switch" />
Also add the following JavaScript just below the code we added in the last step (inside the ready function), and save the file:
$('#article-switch').click(function () {
$('article').toggleClass('newClass');
});
Refresh your index.html document, and then click on the Article Tag Switch button, as displayed in Figure D shown in Chrome 17.0.9:
Notice in this instance that we are finding the element with id of article-switch (the Article Tag Switch button), and when we click on the Article Tag Switch button, the two elements with the “article” tag are affected by the jQuery toggle to “newClass”, which transforms them to the green shadow box styles.
Get Objects by Attribute .attr ( attributeName )
We can get any attribute (id, class, style, name, title) of any tag (ex: <section>, <article>, <p>, <a href>) using the .attr(“attributeName”) function. This method returns a string of the element’s attribute.
According to the description for the jQuery’s .attr() method to get the value of an element’s attribute, it has two main benefits:
- Convenience: It can be called directly on a jQuery object and chained to other jQuery methods.
- Cross-browser consistency: The values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies.
In this example, we will change a displayed image using jQuery to replace an image source file, along with the alt and title, but first we will add in the following to our index.html file just below the Article Button line:
<section id="images">
<p><strong>Images</strong></p>
<img src="images/Orchid.gif" title="Orchid" alt="Orchid" >
</section>
<input type="button" id="image-switch" value="Attribute Switch" />
We will use jQuery to change the image source, the alt attribute, and the title attribute. At the same time, we will pass the sets of names and values into the method at once using a map — .attr( map ) . A map of attribute-value pairs to set each key-value pair in the map adds or modifies an attribute. Add the following jQuery to the event handler just below the previous code in the index.html file, and then save the file:
$('#image-switch').click(function (){
$('img').attr ({
src: "images/Rose.gif",
alt: 'Rose',
title: 'Rose'
});
});
We will also add in the following styles into the styles.css file, save this file again:
#images {
border: 3px solid gray;
padding:10px;
width:400px;
}
Before our Attribute Switch button is clicked this is how the index.html document appears as viewed in Figure E in Chrome 17.0.9:
Click the Attribute Switch button, and the image will update to the rose displayed in Figure F as viewed in Chrome 17.0.9:
In our next segment on jQuery, we will cover filtering objects, changing CSS classes, changing an object’s inner text, and other fun stuff!