3

I know how to add a css element to a header using JS but how do I remove one?

To add :

var style = document.createElement('style');
style.type = 'text/css'; 
style.innerHtml = ".item {color:red}";
document.getElementsByTagName('head')[0].appendChild(style);

My question is how can I remove the element, I tried

document.getElementsByTagName('head')[0].removeChild(style);

It throws up an error, I want to remove the css and not throw an error if it doesn't exist.

Your help is most appreciated.

I do not want to use JQuery.

The actual solution based on Daniels that I used is :-

        var DeskTag = document.getElementById('style');

        if (DeskTag!=null) {
            document.getElementsByTagName('head')[0].removeChild(DeskTag);
        }
2
  • Are you saying your removal code works if it exists, but you are only getting the error when it doesn't exist? Commented Sep 15, 2020 at 19:14
  • You should be using textContent, not innerhtml (or even the correctly spelled innerHTML). Commented Sep 15, 2020 at 19:21

3 Answers 3

4

You could give it an id and access it directly:

style.id = 'style-tag'
const styleTag = document.getElementById('style-tag');
if (!styleTag) return;
document.getElementsByTagName('head')[0].removeChild(styleTag);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Dan, I got it work using the method above, slightly different coding but if it hadn't been for the answer, I wouldn't have cracked it.
0

The answer for this question is just as simple as you do the following: instead of using .removeChild(style);

First let's simulate we add the style:

    var style = document.createElement('style');
    style.type = 'text/css'; 
    style.innerhtml = ".item {color:red}";
    document.getElementsByTagName('head')[0].appendChild(style);

Then let's remove it:

function removeStyle(){
  style.innerHTML = ""; // you just need to reset the style as it was: blank
  document.getElementsByTagName('head')[0].appendChild(style);
}
removeStyle();

If this doesn't work, I hope it gives you an idea of what you can do.

Comments

0

if there is only the one 'style' tag, use

document.querySelector('style').remove()

in case there could be a bunch of them, add a class for each:

const style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = ".item {color:red}";
style.classList.add('style_to_delete')
document.getElementsByTagName('head')[0].appendChild(style);
document.querySelector('.style_to_delete').remove()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.