DEV Community

Cover image for How to get all the external CSS stylesheets links from a webpage using JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to get all the external CSS stylesheets links from a webpage using JavaScript?

Originally posted here!

To get all the external CSS stylesheets links of a webpage using JavaScript, you can use the href property of each item in the document.styleSheets array-like list.

For example, if you want to get all links of the external CSS stylesheets of the google.com homepage.

You can do it like this,

TL;DR

// array to hold all css href's
const allCssStylesheetsLinks = [];

// get refernce to all stylesheets
const stylesheets = document.styleSheets;

// looping through each stylesheet
// and checksing if there is href property in each item
for (let i = 0; i < stylesheets.length; i++) {
  if (stylesheets[i].href) {
    allCssStylesheetsLinks.push(stylesheets[i].href);
  }
}

// logging the array of stylesheets links
console.log(allCssStylesheetsLinks);
Enter fullscreen mode Exit fullscreen mode

Explanation

  • First, we can define an array to hold all the external CSS stylesheets links
// array to hold all css href's
const allCssStylesheetsLinks = [];
Enter fullscreen mode Exit fullscreen mode
  • After that let's get a reference to the stylesheets
// array to hold all css href's
const allCssStylesheetsLinks = [];

// get reference to all stylesheets
const stylesheets = document.styleSheets;
Enter fullscreen mode Exit fullscreen mode

Next, we can loop through each stylesheet and check if the href property is present in each of the styleSheets list items. If the href has a truthy value we push the href property value to the allCssStylesheetsLinks array.

It can be done like this,

// array to hold all CSS href's
const allCssStylesheetsLinks = [];

// get refernce to all stylesheets
const stylesheets = document.styleSheets;

// looping through each stylesheet
// and checking if there is href property in each item
for (let i = 0; i < stylesheets.length; i++) {
  if (stylesheets[i].href) {
    allCssStylesheetsLinks.push(stylesheets[i].href);
  }
}
Enter fullscreen mode Exit fullscreen mode

Now all the href are available in the allCssStylesheetsLinks array.

// array to hold all css href's
const allCssStylesheetsLinks = [];

// get refernce to all stylesheets
const stylesheets = document.styleSheets;

// looping through each stylesheet
// and checksing if there is href property in each item
for (let i = 0; i < stylesheets.length; i++) {
  if (stylesheets[i].href) {
    allCssStylesheetsLinks.push(stylesheets[i].href);
  }
}

// logging the array of stylesheets links
console.log(allCssStylesheetsLinks);
Enter fullscreen mode Exit fullscreen mode

That's it! 😃.

See the above code live in JSBin

Feel free to share if you found this useful 😃.


Top comments (0)