Intro
As a little refresher here, attributes are the data in an element to defines the element. For example, and <img> element's attributes are src, alt and others. An <a> element would have attributes like href, and maybe target.
To get the current value of an attribute, we use the following syntax:
- $("element").attr("currentAttribute");
- $("img").attr("src");
To set, or change an attribute, we simply add a second input:
- $("element").attr("currentAttribute", "newAttributeToSet");
- $("img").attr("currentSrc", "newSrc");
Now remember, when selecting an element, like the <img> element in this example, we are selecting ALL of the like elements on the page. So if you only want to select one element, you must refine your query using a class, id, or other selector method, to limit the scope of your query.
One last note here.
Remember that a class, or ID are also attributes, so we can also use the attr method to change these. If we set:
- $("element").attr("class");
- $("element").attr("class", "newClass");