Performance: Attribute selectors
Attribute selectors affect CSS matching speed and rendering performance, especially on large DOMs.
Jump into concepts and practice - no test required
.button { color: blue; }
[data-role='button'] { color: blue; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| [data-role='button'] | Checks attributes on many elements | 0 (style only) | Low to medium | [X] Bad |
| .button | Matches elements by class quickly | 0 (style only) | Low | [OK] Good |
[type="text"] select?[type="text"] targets elements that have an attribute named type with the exact value "text".type equal to "text" -> Option Binput elements with a placeholder attribute?[attribute]. So input[placeholder] selects all input elements with a placeholder attribute.input.placeholder selects inputs with class "placeholder"; input#placeholder selects input with ID "placeholder"; input(placeholder) is invalid CSS syntax.a[href^="https"] { color: green; } and the HTML below, which links will appear green?<a href="https://example.com">Link 1</a>
<a href="http://example.com">Link 2</a>
<a href="https://secure.com">Link 3</a>
<a href="ftp://example.com">Link 4</a>[href^="https"]a elements whose href attribute starts with "https".img elements with an alt attribute ending with ".jpg". Why does it not work?img[alt*=".jpg"] { border: 2px solid red; }*= means "contains" anywhere, $= means "ends with", ^= means "starts with".alt attribute ends with ".jpg", we must use $= instead of *=.*= to $= to match the end of the attribute -> Option Abutton elements that have a data-action attribute starting with "save" but only if the attribute value is exactly "save" or starts with "save-" (like "save-draft"). Which CSS selector correctly achieves this?data-action is exactly "save" OR starts with "save-".[data-action="save"] matches exactly "save".[data-action^="save-"] matches values starting with "save-".[data-action^="save"] matches any value starting with "save", including "savegame" which is not desired.[data-action*="save"] matches anywhere "save" appears, too broad.[data-action$="save"] matches values ending with "save", not what we want.