As I'm dynamically generating elements and adding them to the page, each element needs a unique numerical id
. However, due to non-linear removal of elements, there can be gaps in the assigned ids. For example...
In one scenario: 1
, 3
, 4
, 5
, 16
, 22
.
In such a case, if a new element is created, it should be given an id
of 2
.
Another scenario: 3
, 4
, 5
.
In this instance, the next available id would be 1
.
Although the code provided seems functional, it appears overly complex. Any suggestions on how to simplify it?
const divs = element.getElementsByTagName('div')
for (let i = 0; i < divs.length; i++) {
if (i > 0 && Number(divs[i].id) > Number(divs[i-1].id)+1 ) {
return Number(divs[i-1].id)+1
break
} else if (i === divs.length-1) {
return Number(divs[divs.length-1].id)+1
} else if (Number(divs[0].id) > 1) {
return 1
break
} else if (divs.length === 1 && Number(divs[0].id) === 1) {
return 2
} else if (divs.length === 1 && Number(divs[0].id) !== 1) {
return 1
}
}
Following elsyr's suggestion, I now track the IDs. This allows for a more optimal approach as shown in the updated code below.
const lowestNum = lowestId()
div.id = lowestNum
numericalIds[lowestNum-1] = lowestNum
function lowestId(){
for (let i = 0; i < numericalIds.length; i++) {
if (!numericalIds[i]) {
return i+1
} else if (i === numericalIds.length-1) {
return numericalIds[numericalIds.length-1]+1
}
}
return 1
}
Prior to removing elements from the page, ensure to update the array accordingly.
numericalIds[/*numerical value of id*/-1] = 0 // or null or undefined
This method guarantees that IDs are assigned starting from the smallest available number greater than or equal to 1
.