Created
June 6, 2017 20:40
-
-
Save leonsomed/7b2aaf797dba6de6825db9595aec584e to your computer and use it in GitHub Desktop.
Scan DOM attribute changes changes
This file contains hidden or 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
| var scan = (function(attributes){ | |
| var hashes = {}, | |
| counter = 100000, | |
| CUSTOM_ID_ATTR = 'custom-id-attr-' + (Math.random() * 10000) | |
| function scan(root) { | |
| // if no root element provided then use the body element | |
| root = root ? root : document.getElementsByTagName('body')[0] | |
| var all = root.getElementsByTagName("*"), | |
| diff = [], | |
| keys = Object.keys(all) | |
| keys.forEach(function(key) { | |
| var n = all[key], | |
| customId = n.getAttribute(CUSTOM_ID_ATTR), | |
| tmp = '' | |
| attributes.forEach(function(att, i) { | |
| var val = n.getAttribute(att) | |
| tmp += val ? (att + ':' + val) : (att + ':') | |
| if(attributes.length - 1 > i) | |
| tmp += '|' | |
| }) | |
| if(!customId) { | |
| // new element | |
| customId = counter++ | |
| n.setAttribute(CUSTOM_ID_ATTR, customId) | |
| hashes[customId] = tmp | |
| diff.push({ element: n, oldHash: null, newHash: tmp }) | |
| } | |
| else { | |
| if(hashes[customId] != tmp) { | |
| var differences = '' | |
| var oldHash = hashes[customId].split('|') | |
| var newHash = tmp.split('|') | |
| for(var x = 0; x < attributes.length; x++) { | |
| if(oldHash[x] != newHash[x]) | |
| differences += newHash[x] + '|' | |
| } | |
| var index = differences.lastIndexOf('|') | |
| if(index === differences.length-1) | |
| differences = differences.substring(0, index) | |
| diff.push({ element: n, oldHash: hashes[customId], newHash: tmp, diff: differences}) | |
| hashes[customId] = tmp | |
| } | |
| } | |
| }) | |
| return diff | |
| } | |
| scan() | |
| return scan | |
| })(['class', 'style', 'id']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment