Encountering issue with accessing ids of dynamically generated HTML elements using javascript
In my current project, I am attempting to dynamically alter the ids of div elements and remove buttons that are appended to the parent div. The desired functionality is such that when a user clicks on a button with the id removeButton2
, I want the id of removeButton3
to be updated to removeButton2
, and the id of removeButton4
to be changed to removeButton3
. Essentially, after removing the buttons, the ids should be adjusted accordingly. However, I am encountering an issue where I keep getting a null value returned. I am unable to determine the reason behind this error. Below is the code snippet I am currently utilizing:
var removeButtonCounter =0;
var divCounter=0;
var addButtonClickCount=0;
$('#AddButton').on('click',function()
{
removeButtonCounter++; divCounter++;addButtonClickCount++;
$('#diplayContainerDiv').append('<div id="divQueryDisplay'+ divCounter +'"></div><div id="removeButtonDiv"><input type="button" value="Remove" name="removeButton" id="removeButton'+ removeButtonCounter +'"> </div>');
$("#removeButton" + removeButtonCounter).click(function() {
var myId = this.id;
var lastChar = myId.slice(-1);
valRemoveButtonClickLastChar = lastChar;
$(this).remove();
var i=valRemoveButtonClickLastChar;
while(i<=addButtonClickCount)
{
document.getElementById(myId).id="removeButton"+i; // null value is being passed
document.getElementById("divQueryDisplay"+(parseInt(i)+1)).id="divQueryDisplay"+i; // null value is being passed here
i++;
}
});
});
The error message received reads as follows:
Uncaught TypeError: Cannot set property 'id' of null