Last active
August 29, 2015 14:04
-
-
Save ComFreek/0ea3de26530f0d85ceb4 to your computer and use it in GitHub Desktop.
Bookmarklet: Show HTML tags occurrences
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.)