Rogier
Rogier

Reputation: 152

Will adding an id to a html style tag cause issues?

I have a javascript application where for some obscure reasons I need to:

My simplified setup I have right now is something like this...


Injecting the <style ...> tag:

const css = `
  * {
    outline: 2px dashed lime;  
  }
`;

const styleEl = document.createElement('style');

styleEl.id = 'myid';

document.head.appendChild(styleEl);

styleEl.appendChild(document.createTextNode(css));

And at another time I want to remove those styles again, using the id I assigned to identify the <style ...> tag, because a lot of other style nodes are in the head:

const styleElement = document.getElementById('myid');

if (styleElement && styleElement.parentNode) styleElement.parentNode.removeChild(styleElement);

I think the id on the <style ...> tag is not valid HTML. But can also not think of another elegant way of solving this. I cannot use inline styles in this case, because the styles should apply the whole document (actually targeting an injected iframe).

Thoughts and help is much appreciated!

Upvotes: 0

Views: 388

Answers (1)

justMatys
justMatys

Reputation: 112

You don't have to get it by id again. You have it in styleEl variable, so just remove it from a DOM like this:

styleEl.remove(); // remove it from the DOM

You can do this repeatedly. Append and remove.

Upvotes: 1

Related Questions