Target ID, class, or data attributes for JavaScript
colorful-tones opened this issue · 2 comments
From "Markup" > "Classes & IDs"
When using JavaScript to target specific elements in your markup, prefix the ID of the element that is being targeted with js-. This indicates the element is being targeted by JavaScript for your future self as well as other developers that may work on the project.
Example:
<nav id="js-primary-menu" class="primary-menu"></nav>
I recommend replacing this with use of data attributes. Perhaps it is the old-school Front Ender in me that gets queasy when I see IDs.
<nav class="primary-menu" data-js-primary-menu></nav>
There are some noted "Issues" with using them on MDN Web Docs, but doesn't seem like a barrier for most 10up work. Thoughts?
@colorful-tones I put this PrefTest together for a POC, going into the DOM and grabbing an ID is significantly more performant than using an attribute selector (by 29% when I ran it): https://jsperf.com/id-vs-queryselector/1
IDs are also largely used for accessibility hooks, so we definitely used them a lot, just not for styling.