- What Are HTML Attributes?
- Final Thoughts
HTML attributes are anything that is passed into the HTML tag along with the tag type.
Examples of HTML attributes include:
- HTML classes
- HTML IDs
altattributes for HTML images
As an example, let's consider the
<img> tag that is included at the bottom of our
Since it's the first image included on our webpage, we can easily select the image using the
querySelector method like this:
imageVariable = document.querySelector('img');
The actual image that is rendered to the page from this
<img> tag is specified using the tag's
src attribute. Accordingly, we can modify the image that appears by changing the value of
Take a moment to navigate to Google Images and find an image that you'd like to add to our webpage. Once you've identified an image, grab it's URL by right-clicking and selecting "Copy Image Address". Here's the URL I've selected (which is a picture of Michael Jordan, if you're curious):
imageVariable.src = 'https://www.nba.com/images/cms/2020-03/michael-jordan-iso-archive-blazers.jpg?cw=1920&w=2051&x=96&ch=1080&h=1367&y=251'
Adding new attributes to HTML elements can sometimes introduce bugs if you assign a value to an attribute that is non-standard.
For example, I may want to add some characteristics to the
<img> tag to show that its image was taken from Google Images. However, setting
src=GoogleImages will break the
<img> tag since the
src attribute is meant to hold the URL where the file is uploaded at.
What is the solution to this problem?
Data attributes allow you to create element attributes that have no meaning by default in HTML. These variables are meant to hold data that we, the developers, are using in some custom way.
Data attributes always start with
data-, which tells HTML not to use them in any of its default functionality.
In this case, a useful way to store the source of our image would be to set
data-image-source="Google Images". Data attributes are typically added in the
index.html file of a webpage, so we could create this
data-image-source attribute as follows:
<img src = "[/images/headshot.jpg](/images/headshot.jpg)" data-image-source="Google Images">
If you have an HTML element with multiple data attributes, you can easily access them by calling the
dataset attribute, like this:
This returns a list of all of the data attributes that are applied to an element, similar to how the
classList returns a list of all the CSS classes applied to an HTML element.
Here is a brief summary of what we discussed in this lesson:
- Examples of HTML attributes
- How to select HTML attributes using the dot operator
- How to modify HTML attributes using the
- What data attributes are, and how you can use them to prevent bugs in your code