Data Attributes are useful in the year 2020.
They gives us greater flexibility when we interact with the DOM. Instead of the usual
HTML elements, we can use custom data attributes.
We have a list of users on the side of a chat app — i.e. a buddy list.
We need to update this buddy list depending on what happens elsewhere on the application. Let’s say
jimmy2020 goes offline, we’ll want to tell his friend
erica123 (by updating her buddy list).
If we give
jimmy2020 a data attribute like
Let’s assume we have
jimmy2020 saved in a variable
And unpack the syntax.
In this single line of code, we have:
- square brackets
- equals sign
- double quotes
- dollar sign
- squiggly brackets
We’re just trying to select a measly little element in the DOM, and our brains need to care about the nuanced behaviors of these little characters.
document.querySelector is a function that takes an argument, and function arguments live inside of parens.
This function takes a string as an argument that selects some element in the DOM. This looks like the kind of stuff that you’d use to select HTML in your CSS. Just remember that it needs to be a string.
Our single argument lives inside of back-ticks. Back-ticks are functionally similar to single quotes, or double quotes.
And this argument needs to be a string, so backticks seem reasonable.
But beyond reasonable, they are necessary, because of their 1 main difference from
” — if you want to use string interpolation inside of them.
In other words, if you want to reference a variable inside of a string, use backticks, which we’ll be doing in a second.
Multi-word selectors require hyphens! Not underscores, not camel case, not title case.
As we mentioned before, the argument inside of
querySelector needs to be a string, but so does the value of the
So we have a string inside of a string. If we tried to use backticks, it would prematurely close the initial string, so we have to use something else that represents strings, and double quotes will do the trick.
Dollar Sign / Squiggly Brackets