Created
March 17, 2025 06:43
-
-
Save ahbanavi/aaece18ef1b85122ff8f3037da8f4aa6 to your computer and use it in GitHub Desktop.
find duplicated name in a web page
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
const findDuplicateNames = () => { | |
// Get all form elements excluding radio buttons | |
const elements = document.querySelectorAll('input:not([type="radio"]), textarea, select'); | |
const nameMap = new Map(); | |
elements.forEach(element => { | |
const name = element.getAttribute('name'); | |
if (name) { | |
if (!nameMap.has(name)) { | |
nameMap.set(name, []); | |
} | |
nameMap.get(name).push({ | |
element: element, | |
type: element.type || element.tagName.toLowerCase(), | |
id: element.id || 'no-id', | |
path: getElementPath(element) | |
}); | |
} | |
}); | |
const duplicates = Array.from(nameMap.entries()) | |
.filter(([_, elements]) => elements.length > 1); | |
if (duplicates.length === 0) { | |
console.log('No duplicate name attributes found'); | |
return; | |
} | |
console.group('Duplicate name attributes found:'); | |
duplicates.forEach(([name, elements]) => { | |
console.group(`Name: "${name}" (${elements.length} occurrences)`); | |
elements.forEach((item, index) => { | |
console.log(`${index + 1}. Type: ${item.type}, ID: ${item.id}`); | |
console.log(` Path: ${item.path}`); | |
}); | |
console.groupEnd(); | |
}); | |
console.groupEnd(); | |
}; | |
const getElementPath = (element) => { | |
const path = []; | |
let currentNode = element; | |
while (currentNode) { | |
let selector = currentNode.nodeName.toLowerCase(); | |
if (currentNode.id) { | |
selector += `#${currentNode.id}`; | |
} else if (currentNode.className) { | |
selector += `.${currentNode.className.split(' ').join('.')}`; | |
} | |
path.unshift(selector); | |
currentNode = currentNode.parentElement; | |
} | |
return path.join(' > '); | |
}; | |
findDuplicateNames(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment