What is the best way to achieve separation of concerns between HTML, CSS, and JS using this HTML structure?
<nav role="navigation" class="site-nav js-site-nav">
<ul class="site-nav__list">
<li class="site-nav__item"><a href="#" class="site-nav__link">Menu Item 1</a></li>
<li class="site-nav__item"><a href="#" class="site-nav__link is-active">Menu Item 2</a></li>
</ul>
</nav>
Check out the demo: http://codepen.io/achisholm/pen/wGVGxj
Upon closer inspection, it appears that this example lacks a true separation of concerns. The class naming system does not facilitate easy separation. Even when targeting the links, the .site-nav__link
selector would still be required in the JS.
One possible solution could be to add a JS hook class to each link. Would adding .js-site-nav__link
class to each link enhance the decoupling?
<nav role="navigation" class="site-nav">
<ul class="site-nav__list">
<li class="site-nav__item js-site-nav__item"><a href="#" class="site-nav__link">Menu Item 1</a></li>
<li class="site-nav__item js-site-nav__item"><a href="#" class="site-nav__link is-active">Menu Item 2</a></li>
</ul>
</nav>
However, this solution may not be ideal as using the complete BEM name could still complicate structural changes. Is there a better alternative to just using .site-nav__link
?
Considering a class name like js-link
may be an option, but it could lead to other issues. Would targeting .js-site-nav .js-link
provide the best solution?
<nav role="navigation" class="site-nav">
<ul class="site-nav__list">
<li class="site-nav__item js-link"><a href="#" class="site-nav__link">Menu Item 1</a></li>
<li class="site-nav__item js-link"><a href="#" class="site-nav__link is-active">Menu Item 2</a></li>
</ul>
</nav>
While this feels like a more separated approach, is it the most effective solution?
Special thanks to @claudios for providing an example with a clear JS hook using js-add
. This method might work well, but may not be suitable for all scenarios. Perhaps a JS hook like js-toggle-link
could lead to a better structured approach.
Reference: HTML structure derived from the following talk (relevant part at 17 mins)...