I use CSS isolation.
This is the output html code:
<div b-1yc1hoca3 class="test">Text</div>
.test {
border: 1px solid red;
}
Random string that CSS isolation generates is: b-1yc1hoca3
I add some html code after page loaded.
$('#main').append(`<div class="test">Text</div>`);
When above codes will be add, above codes doesn't have CSS isolation random string (b-1yc1hoca3
) and CSS codes doesn't apply to the element.
How can I get CSS isolation random string with JQuery
to added to below codes:
$('#main').append(`<div class="test">Text</div>`);
Just only thing I need is b-1yc1hoca3
.
For example
var cssIsolationRandomString = $('.test').attr('cssIsloationRandomString');
$('#main').append(`<div ${cssIsolationRandomString} class="test">Text</div>`);
As far as I know, all CSS isolation random string starts with b-
.
The problem is CSS isolation random strings
are random strings and I don't know how to get a random attribute that start with b-
First of all, I found a github issue here which mentioned CSS isolation is a build time process
, and the isolation string is generated by framework.
Within the bundled file, each component is associated with a scope identifier. For each styled component, an HTML attribute is appended with the format b-{STRING}, where the {STRING} placeholder is a ten-character string generated by the framework.
Therefore, we can't use Jquery to generate the random string and use it when append the dynamic content. But I found that the random string in the page are the same when the page is rendered. So when we append the dynamic content, we can first to get the b-{string}
from the initial existed DOM element, then use it in the new content, this worked for me.
<div id="dynamicContent">
<p id="targetItem">hello this is content in red</p>
</div>
<button id="add">add section</button>
@section Scripts{
<script>
$("#add").click(function(){
var attrs = document.getElementById("targetItem").attributes;
console.info(attrs);
var isolation = "";
$.each(attrs,function(i,elem){
if (elem.name.startsWith("b-")){
isolation = elem.name;
}
});
$('#dynamicContent').append("<p "+isolation+" >added content</p>");
})
</script>
}