Here i'm trying to remove the link tags from head based on the flag value. based on the flag value i'm removing the link tags from head and creating new tags.
in the below code whats happening is i'm able to remove only the last link tag, but not all the link tags from the head tag. not sure why its happening.
Here is what i have tried.
let bootstrapTheme = true;
let head = document.getElementsByTagName('head')[0],
stylesheets = ['https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js','https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js']
var link;
stylesheets.forEach(function(stylesheet) {
link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = stylesheet;
head.appendChild(link);
});
if(!bootstrapTheme){
link.parentNode.removeChild(link);
}
Well you could store all the links you create in an array and then iterate over them and remove them:
let bootstrapTheme = true;
let head = document.getElementsByTagName('head')[0],
stylesheets = ['https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js','https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js']
var links = [];
stylesheets.forEach(function(stylesheet) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = stylesheet;
head.appendChild(link);
links.push(link);
});
if(!bootstrapTheme){
links.forEach(function(link) {
link.parentNode.removeChild(link);
});
}
But if I were you, I would simply wrap the first .forEach() in the if and wouldn't add the links if not necessary:
let bootstrapTheme = true;
let head = document.getElementsByTagName('head')[0],
stylesheets = ['https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js','https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js']
if (bootstrapTheme) {
stylesheets.forEach(function(stylesheet) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = stylesheet;
head.appendChild(link);
});
}
I would do this the following way.
Step 1: List all link tags in an Array
Step 2: Remove all elements listed in the Array
var list = document.head.getElementsByTagName("link");
var num= list.length;
for ( var i =0; i<num; i = i++){
head.removeChild(list[i]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With