Quick Tip — Written on
One-line HTML stats with JavaScript
That tip from Lea Verou on Twitter to get all the used elements on an HTML page is pretty great. Why? Well, to gain some knowledge about how semantically diverse your HTML is.
Distinct elements on your page
To get a list with the unique names of tags on a specific page you can do this:
let names = [...new Set($$("*").map(e => e.nodeName.toLowerCase()))];
On this specific page, the names
array will contain this (at the time of writing):
[
"html","head","meta","title","link","body","a","header","svg","path","nav","ul",
"li","main","article","p","span","time","h1","div","pre","code","footer","section",
"h2","figure","script"
]
These are 27 tags. Ok, fine. Now that includes all the rubbish in the <head>
. Let's get only the names in the <body>
:
let names = [...new Set($$("body *").map(e => e.nodeName.toLowerCase()))];
This will yield this list:
[
"a","header","svg","title","path","nav","ul","li","main","article","p",
"span","time","h1","div","pre","code","footer","section","h2","figure",
"script"
]
Fine, now we are down to 22 tags. How exciting (I'm weird I know). Now a fancy little trick with flatMap
:
let classes = [...new Set($$("[class]").flatMap(e => [...e.classList]))];
That will show you all the shoddy classes you hacked together:
[
"js","PostLayout","PostLayout_quickTip","_visuallyHidden","Header",
"Header-LogoLink","Graphic","FullLogo","Header-Menu","MainMenu",
"MainMenu-List","inline","MainMenu-Item","MainMenu-Link","MainContent",
"FullPost","FullPost-Header","FullPost-Meta","FullPost-Category",
"FullPost-PubDate","FullPost-Headline","FullPost-Content",
"language-javascript","Footer","Footer-Text","Footer-Menu",
"List-Item","Footer-Legal","Footer-Logo","JFrLogo"
]
Uhh, I might want to reduce this soon … Anyway what I learned is that you can do a lot of very awesome things in modern browsers—and in just a single line of code.