Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the link tag from the head using javascript?

Tags:

javascript

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);
    }
like image 657
CJAY Avatar asked Oct 25 '25 02:10

CJAY


2 Answers

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);
    });
}
like image 103
Sebastian Kaczmarek Avatar answered Oct 26 '25 18:10

Sebastian Kaczmarek


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]);

}

like image 39
Gnomejodas Avatar answered Oct 26 '25 18:10

Gnomejodas