When writing custom elements, and don't want to use 'shadow DOM', it's not obvious to avoid name clashing.
A way to solve this problem is to 'namespace' your class names.
But how to dynamically apply this namespace ?
In the following code, I use the nice little function ustyler.
I also use DML, but feel free to use (or no) whatever framework you want.
you can test it here NSCss
Here is the main function :
const nameSpace = "AppName";
let setClass = (classname,color) => {
let ns = `${nameSpace}-${classname}`
css`.${ns} {
color : ${color};
font-size: 24px;
}`
return ns;
}
<html lang="de">
<head>
<meta charset="utf-8">
<title>title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://efpage.de/DML/DML_homepage/lib/DML-min.js"></script>
</head>
<div class="header">
My class name is 'header', defined globally
</div>
<hr />
<div id="myapp">
</div>
<body>
<script>
function css(template) {
var text = typeof template == 'string' ? [template] : [template[0]];
for (var i = 1, length = arguments.length; i < length; i++) {
text.push(arguments[i], template[i]);
}
var style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(text.join('')));
return document.head.appendChild(style);
}
const nameSpace = "AppName";
let setClass = (classname,color) => {
let ns = `${nameSpace}-${classname}`
css`.${ns} {
color : ${color};
font-size: 24px;
}`
return ns;
}
selectBase(myapp)
print(`<h1 class="${setClass('header','red')}">My class name is : '${nameSpace}-header', defined dynamically</h1>`)
unselectBase()
</script>
</body>
</html>
You can see the result in the inspector :