A Few Document Collection Helpers
Here are a few document helper methods I never heard about until recently:
- document.links: Returns a collection of all
<area>
and<a>
elements with a value in thehref
attribute. - document.styleSheets: Returns a StyleSheetList of all stylesheets linked to or embedded in a document.
- document.forms: Returns an HTMLCollection of all the
<form>
elements in a document. - document.scripts: Returns an HTMLCollection of all the
<script>
elements in a document. - document.images: Returns a collection of all the images in an HTML document.
Conveniently, all of these except styleSheets return an HTMLCollection. Which has two important methods, item() which you can use to query by index. And namedItem(), which will find the element by ID, or as a fallback, the name attribute.
const links = document.links; // HTMLCollection(4) [a, a, a, a]
links.namedItem('GitHub').href; // https://github.com/eglove
links.item(3).href; // https://www.linkedin.com/in/ethan-glover/
Of course, StyleSheetList does not have a named item method, so you're stuck with having to determine which is which by looping over the stylesheets and using something like a title attribute.
for (let sheet of document.styleSheets) {
if (sheet.title === 'PicoCSS') {
console.log(sheet.href); // https://cdn.jsdelivr.net/npm/@picocss/pico@latest/css/pico.slate.min.css
break;
}
}