CSS Classes for JavaScript querySelector

March 29, 2024

._camelCase class naming convention is a great substitute for an element's ID to be used in JavaScript.

Example:

html
<div class="widget-FeaturedPost _wgFeaturedPost">
  <!-- content goes here -->
</div>

<style>
  .widget-FeaturedPost {
    background: lightblue;
  }
</style>

<script>
  // replace ._wgFeaturedPost text to "Foo bar"
  let el = document.querySelector('._wgFeaturedPost');
  el?.replaceChildren('Foo bar');
</script>

Pros:

  • Definitely not used for styling.
  • Easily distinguishable from hyphens classes such as .bg-red, .m-auto, etc.
  • Easy to spot and search in the codebase.
  • Easily copied by double-clicking on the class name on the element inspector.

Cons:

  • Exposing an easy-to-guess JavaScript objects and processes.

Tips

Put it as the last element's classes. This way you can easily copy the class name by double-clicking it in the element inspection tool.

Double-clicking class name to copy. 

Comments

Thank You

for your visit