Here's a JavaScript script that:
- Starts from the element with ID
#container.
- Recursively scans all child nodes.
- For each node that doesn't have an
id, assigns one based on:
- The closest ancestor with an
id (or itself if it has one)
- Appended with a hyphen, a unique counter, and the tag name.
This ensures that even deeply nested elements without IDs get unique ones derived from their nearest parent with an ID.
✅ Example Use Case
Given this structure inside #container:
<ul id="drw-item1">
<li>
<strong>Fusion F7 Power</strong>: Aktuell bei
<strong style="color:#dc4d01;">27 %</strong>. Kritischer Stand voraussichtlich um
<em style="color:#dc4d01;">8:31:30</em> (am 15.06.2025, 17:30 Uhr).
</li>
</ul>
After running the script, it will assign IDs like drw-item1-strong1, drw-item1-strong2, drw-item1-em, etc., to the inner elements.
🧠 JavaScript Code
function assignUniqueIds(node, parentEffectiveId = null) {
// Keep track of how many times each tag appears under a given ID
const tagCountMap = {};
function traverse(currentNode) {
// Only process element nodes (nodeType === 1)
if (currentNode.nodeType !== Node.ELEMENT_NODE) return;
let currentId = currentNode.id;
let currentParentId = parentEffectiveId;
// If this node has its own ID, use it as the new base for children
if (currentId) {
currentParentId = currentId;
} else if (currentParentId) {
// Generate a new ID if none exists
const tagName = currentNode.tagName.toLowerCase();
const key = `${currentParentId}-${tagName}`;
// Initialize or increment count per tag
tagCountMap[key] = (tagCountMap[key] || 0) + 1;
currentNode.id = `${key}${tagCountMap[key] > 1 ? tagCountMap[key] : ''}`;
}
// Traverse children
for (const child of currentNode.children) {
traverse(child, currentParentId);
}
}
traverse(node);
}
// Start the process on the container element
document.addEventListener("DOMContentLoaded", function () {
const container = document.getElementById("container");
if (container) {
assignUniqueIds(container);
}
});
📝 Notes
- This script handles deep nesting correctly by always using the closest parent with an ID.
- It ensures uniqueness by tracking how many times each tag appears under a given parent ID.
- If only one
<strong> is found under a parent ID, it becomes parent-strong, not parent-strong1. The number is added only when needed.
🔁 Optional Enhancement
If you want every tag to be numbered consistently (e.g., always strong1, strong2, even if only one), just change this line:
currentNode.id = `${key}${tagCountMap[key] > 1 ? tagCountMap[key] : ''}`;
to:
currentNode.id = `${key}${tagCountMap[key]}`;
Let me know if you'd like this version instead!