Complete 2024 Web Development Bootcamp

Dr. Angela Yu

Back to jQuery Index Page


jQuery & Attributes
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");
so if we set:
  • $("img").attr("src");
it will return the current image's source, if there is one. (if the src is set in JavaScript, it may not be defined yet).

To set, or change an attribute, we simply add a second input:

  • $("element").attr("currentAttribute", "newAttributeToSet");
so we might say:
  • $("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");
would return all of the classes associated with the element(s), and:
  • $("element").attr("class", "newClass");
would assign a new class to the element(s).


Back to Top