Skip to content

Instantly share code, notes, and snippets.

@ComFreek
Last active August 29, 2015 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ComFreek/0ea3de26530f0d85ceb4 to your computer and use it in GitHub Desktop.
Save ComFreek/0ea3de26530f0d85ceb4 to your computer and use it in GitHub Desktop.
Bookmarklet: Show HTML tags occurrences
/**
* A bookmarklet, which displays the number of occurrences of each HTML tag in the DOM
*
* @author ComFreek
* @license MIT
* @link http://softwarerecs.stackexchange.com/a/10329/583
*/
function getTagCounts() {
var treeWalker = document.createTreeWalker(document.documentElement, NodeFilter.SHOW_ELEMENT);
var tagCounts = {};
while (treeWalker.nextNode()) {
var node = treeWalker.currentNode;
if (!(node.tagName in tagCounts)) {
tagCounts[node.tagName] = 0;
}
tagCounts[node.tagName]++;
}
return tagCounts;
}
function convToArray(tagCounts) {
// to array
var tags = [];
for (var tagName in tagCounts) {
if (tagCounts.hasOwnProperty(tagName)) {
tags.push({tagName: tagName, count: tagCounts[tagName]});
}
}
return tags;
}
function sortCompareFn(tagA, tagB) {
if (tagA.count > tagB.count) {
return -1;
}
else if (tagA.count < tagB.count) {
return 1;
}
else {
return 0;
}
}
function arrayToSimpleStr(tags) {
// output
var str = "";
for (var i=0; i<tags.length; i++) {
str += tags[i].tagName;
str += ": ";
str += tags[i].count;
str += "\n";
}
return str;
}
var sortedTagCounts = convToArray(getTagCounts()).sort(sortCompareFn);
alert(arrayToSimpleStr(sortedTagCounts));
Bookmarklet: Show HTML tags occurrences
Tested with:
- Google Chrome
- Mozilla Firefox
Does not work with (yet): IE 11
License: MIT
Author: ComFreek
Written for: http://softwarerecs.stackexchange.com/questions/10290/html-element-statistics-of-the-current-page
@unor
Copy link

unor commented Aug 3, 2014

Very nice :) Thanks for your work, ComFreek! As far as I tested, it works great.

Just in case you’d like to improve it: I think it would be useful to sort the elements alphabetically, when they have the same count. (I used this sort in the example in my question, but didn’t specify it as requirement, as it’s just nice to have but not required.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment