How can you manage CSS selectors for identical code included multiple times in the same page?

I frequently create web apps that use traditional tabs at the top of the page. When doing this, I have a common problem I have been unable to find an elegant solution to.

The problem is the user can load the same content in two separate tabs on the same page. Any HTML ID’s on these two different tabs then conflict, causing any JavaScript referencing one of those ID’s to fail on the second tab. In addition, any JavaScript referencing a class on one of these pages will affect elements on all tabs, when I really only want it to affect the current tab.

For example, what if I included this block of code twice in the same page?

<style>
    #container { margin; 20px; }
    #message { background: red; }
</style>

<div id='container'>
    <span id='message'>This was from an include file</span>
    <button id='changeColorBtn'>Change color</button>
</div>

<script>
    $('#changeColorBtn').click(() => $('#message').css('background', 'blue'))
</script>

JSFIDDLE to illustrate the problem: https://jsfiddle.net/dillydadally/2njcq9py/

I have tried or considered three approaches to solve this in the past:

  1. I tried appending a page id to every element in the included content using PHP. This become messy quick and annoying to write out.

  2. I tried making each tab an iframe. At first, this seemed to work well, but quickly became a management nightmare having that many iframes open on the same page that sometimes needed to communicate with each other and share data. I ran into multiple issues and decided not to attempt this approach again.

  3. I considered wrapping each instance of included content in a single element with a unique ID, but I decided I would run into similar issues as option 1 above. Every CSS selector would have to have that element with the ID first, yet again creating messy code and possibly slowing the page down with numerous multi-depth JQuery selectors. In addition, there would still be multiple elements with the same ID on the same page (although I’m not sure that would matter since every selector should have a parent element included).

Is there an element or approach created to address this problem already in HTML/CSS that I’m missing?

88 thoughts on “How can you manage CSS selectors for identical code included multiple times in the same page?”

Leave a Comment