PentaKon
PentaKon

Reputation: 4636

Browser only applies css from first dynamically added style element

Please view the following code:

let elStyle = document.createElement('style');
elStyle.type = 'text/css';
elStyle.title = "dynamic";
elStyle.innerHTML = ".testclass{padding: 50px;}";
document.head.appendChild(elStyle);

elStyle = document.createElement('style');
elStyle.type = 'text/css';
elStyle.title = "dynamic2";
elStyle.innerHTML = ".testclass2{margin: 50px;}";
document.head.appendChild(elStyle);

let divel = document.createElement('div');
document.body.appendChild(divel);
divel.classList.add('testclass');
divel.classList.add('testclass2');

It dynamically creates two distinct <style> elements and appends them to the dom's head. Afterwards, a <div> element is created dynamically as well and is appended to the dom's body. Then we add to the div element both classes contained respectively in our dynamically added style elements.

In Chrome and Firefox, if you inspect the div element you will see that only the CSS for the first class (testclass) is applied (in our case a padding: 50px;). In MSEdge, both classes' CSS is properly applied.

Is this intended behavior for Chrome/FF or bug?

Upvotes: 0

Views: 39

Answers (1)

Quentin
Quentin

Reputation: 944052

This has nothing to do with the elements being dynamically added.

You have given the style elements titles, which marks them as being alternative stylesheets which shouldn't be used together.

If you remove the title attributes, both will apply.

let elStyle = document.createElement('style');
elStyle.type = 'text/css';
elStyle.innerHTML = ".testclass{padding: 50px;}";
document.head.appendChild(elStyle);

elStyle = document.createElement('style');
elStyle.type = 'text/css';
elStyle.innerHTML = ".testclass2{margin: 50px;}";
document.head.appendChild(elStyle);

let divel = document.createElement('div');
document.body.appendChild(divel);
divel.classList.add('testclass');
divel.classList.add('testclass2');

Upvotes: 1

Related Questions