javascript - 如何使用javascript从头部删除链接标签?

标签 javascript

我在这里尝试根据标志值从 head 中删除链接标签。根据标志值,我从 head 中删除链接标签并创建新标签。

在下面的代码中,我只能删除最后一个链接标签,但不能删除 head 标签中的所有链接标签。不确定为什么会这样。

这是我尝试过的。

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

最佳答案

好吧,您可以将创建的所有 link 存储在一个数组中,然后遍历它们并删除它们:

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

但如果我是你,我会简单地将第一个 .forEach() 包装在 if 中,如果不需要则不会添加链接:

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

关于javascript - 如何使用javascript从头部删除链接标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60944619/

相关文章:

javascript - 如何使 withLatestFrom() 与自身一起工作?

javascript - HTML5 Canvas 在完成呈现时会发出事件吗?

javascript - 不要使用 Router React js 渲染搜索组件

javascript - React Router With Handler 显示空白页面

javascript - 如何在fabricjs中选择位于另一个形状边界内的形状?

javascript - 为目标 div 设置默认内容

javascript - JS Keydown 在第一个事件之后触发事件之前有一些奇怪的 1 秒延迟

javascript - <div> 的大小应始终保持不变

javascript - 使用 HtmlUnit 提交表单

javascript - 如何连接两个 getElementsBy