Search code examples
javascripthtmlcssgetelementsbytagname

Disable a "link" tag without access to HTML


So I have a website I'm working on and in one part we have an embedded newsletter signup. The problem is that the embedded code uses all its own stylesheets which interferes with the design of the site. The embed is done through javascript so I cannot disable them until that section of the page loads.

Basically I need a script to disable an entire <link>. On top of that, the links don't have any classes or ids so they are hard to target.

<link rel=​"stylesheet" type=​"text/​css" href=​"http:​/​/​www.formstack.com/​forms/​css/​3/​default.css?20130404">​

This is one of the links I need to disable. I tried looking for something like a getElementByType or similar but I couldn't find anything.

Any help would be appreciated. As long as the code disables the link that's good enough for me. Maybe there is a way to search the document for the <link> string and surround it with comments?

Thanks guys

PS, I'm a javascript novice and have no idea what I'm doing with js


Solution

  • var test = "http:​/​/​www.formstack.com/​forms/​css/​3/​default.css";
    for (var i = 0; i < document.styleSheets.length; i++) {
        var sheet = document.styleSheets.item(i);
        if (sheet.href.indexOf(test) !== -1) sheet.disabled = true;
    }
    

    this will work, however it is inefficient (still) as it continues to check additional CSSStyleSheets in the CSSStyleSheetList after it has found it's match.

    if you can not care about browser support you can use Array.prototype.some to reduce the number of ops

    [].some.call(document.styleSheets, function(sheet) {
        return sheet.disabled = sheet.href.indexOf(test) !== -1;
    });
    

    see: Array some method on MDN

    edit:
    For a mix of performance AND legacy support the following solution would work:

    var test = "http:​/​/​www.formstack.com/​forms/​css/​3/​default.css";
    for (var i = 0; i < document.styleSheets.length; i++) {
        var sheet = document.styleSheets.item(i);
        if (sheet.href.indexOf(test) !== -1) {
            sheet.disabled = true;
            break;
        }
    }