I have a javascript application where for some obscure reasons I need to:
- Inject styles into my html head
- Remove these styles from my html head at a later stage
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!
CodePudding user response:
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.