Reports IDs that are being used by multiple elements within a page, including the number of occurrences of each one
A Pen by Craig Patik on CodePen.
Reports IDs that are being used by multiple elements within a page, including the number of occurrences of each one
A Pen by Craig Patik on CodePen.
| <!-- Elements to search --> | |
| <div id="abc"></div> | |
| <div id="abcdef"></div> | |
| <div id="abc"></div> | |
| <div id="def"></div> | |
| <div id="def"></div> | |
| <div id="abc"></div> | |
| <!-- Output --> | |
| <ul></ul> |
| var ids = [], // List of known IDs | |
| dupes = [], | |
| $list = $('ul'); | |
| $('body').find('[id]').each(function() { | |
| if (this.id) { | |
| if (!/^[A-Za-z]/.test(this.id)) { | |
| $list.append('<li>The ID <code>#' + this.id + '</code> is not valid; it must begin with a letter</li>'); | |
| } | |
| else { | |
| ids.push(this.id); | |
| } | |
| } | |
| }); | |
| // Count occurences of each ID | |
| $.each(ids, function(i, id) { | |
| var regex = new RegExp('\\b' + id + '\\b', 'g'), | |
| numMatches = ids.join(',').match(regex).length; | |
| if (numMatches > 1 && dupes.indexOf(id) === -1) { | |
| $list.append('<li class="red"><code>#' + id + '</code> is being used in ' + numMatches + ' places</li>'); | |
| dupes.push(id); | |
| } | |
| else if (numMatches === 1) { | |
| $list.append('<li class="green"><code>#' + id + '</code> is NOT duplicated</li>'); | |
| } | |
| }); |
| body { | |
| padding: 0.5em; | |
| } | |
| .red { | |
| color: maroon; | |
| } | |
| .green { | |
| color: #093; | |
| } |
| @import "compass"; | |
| body { | |
| padding: 0.5em; | |
| } | |
| .red { | |
| color: maroon; | |
| } | |
| .green { | |
| color: #093; | |
| } |