Vianne
Vianne

Reputation: 578

Disable all stylesheets inside an element using Javascript

How to disable all external CSS inside of a specific element using StyleSheet.disabled? Not sure if I'm just missing proper syntax. If it's only possible at document level, is there any way I can implement something like this? Thank you.

HTML

<div id="container">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet">

  <i class="material-icons">edit</i>
  <button class="btn btn-primary">Bootstrap</button>
</div>

JS

let el = document.querySelectorAll('#container [rel="stylesheet"]');

for (let i = 0; i < el.length; i++) {
  el.styleSheet[i].disabled = true;
}

Here's a working example with document as default selector: JsFiddle

Upvotes: 1

Views: 64

Answers (2)

KoenW
KoenW

Reputation: 453

I think you made a typo in your code:

let el = document.querySelectorAll('#container [rel="stylesheet"]');

for (let i = 0; i < el.length; i++) {
  el[i].disabled = true;
}

Try this link: https://jsfiddle.net/p0v3rdac/

Upvotes: 1

Rounin
Rounin

Reputation: 29463

You can replace the href attribute with a custom data-href attribute (as a placeholder) :

let elementStylesheets = [... document.querySelectorAll('#container [rel="stylesheet"]')];

for (elementStylesheet of elementStylesheets) {

  elementStylesheet.dataset.href = elementStylesheet.getAttribute('href');
  elementStylesheet.removeAttribute('href');
}

Upvotes: 0

Related Questions