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);
Explanation
- First, we can define an array to hold all the external CSS stylesheets links
// array to hold all css href's
const allCssStylesheetsLinks = [];
- 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;
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);
}
}
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);
That's it! 😃.
See the above code live in JSBin