Here's a JavaScript function that scans all child nodes of #container and assigns unique IDs to elements that don't have one, following your specified pattern:
function assignUniqueIds() {
const container = document.getElementById('container');
if (!container) {
console.error('Container element not found');
return;
}
// We'll use a counter for each tag type to ensure uniqueness
const tagCounters = {};
function processNode(node) {
// Only process element nodes
if (node.nodeType !== Node.ELEMENT_NODE) {
return;
}
// Skip the container itself
if (node === container) {
return;
}
// If the node already has an ID, skip it
if (node.id) {
return;
}
// Get the parent's ID
let parentId = '';
if (node.parentNode && node.parentNode.id) {
parentId = node.parentNode.id;
} else {
// If parent has no ID, we can't create a proper ID for this node
return;
}
// Get the tag name
const tagName = node.tagName.toLowerCase();
// Initialize counter for this tag type if it doesn't exist
if (!tagCounters[tagName]) {
tagCounters[tagName] = 0;
}
// Increment the counter for this tag type
tagCounters[tagName]++;
// Create the new ID
const newId = `${parentId}-${tagName}${tagCounters[tagName]}`;
// Assign the new ID
node.id = newId;
// Process all child nodes recursively
const children = node.childNodes;
for (let i = 0; i < children.length; i++) {
processNode(children[i]);
}
}
// Start processing from the container's children
const children = container.childNodes;
for (let i = 0; i < children.length; i++) {
processNode(children[i]);
}
}
// Call the function to assign IDs
assignUniqueIds();
How This Works:
- The function starts by finding the container element.
- It maintains a counter for each tag type to ensure unique IDs.
- For each node:
- It checks if the node is an element node and doesn't already have an ID.
- It gets the parent's ID (skipping if the parent has no ID).
- It creates a new ID by combining the parent's ID, the tag name, and an incrementing counter.
- It assigns this new ID to the node.
- The function processes all child nodes recursively.
Example Usage:
<div id="container">
<li id="drw-item1">
<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>
</div>
<script>
// Call the function after the DOM is loaded
document.addEventListener('DOMContentLoaded', assignUniqueIds);
</script>
This will transform the HTML as shown in your example, with each element getting a unique ID based on its parent's ID and its tag name.