If you're trying to modify, in an onblur handler, the same node you're trying to remove in another handler (eg onfocus, keydown etc) then the first call to removeChild
will fire the onblur handler before actually removing the node.
If the onblur handler then modifies the node so that its parent changes, control will return from the onblur handler to the removeChild
call in your onfocus handler which will then try to remove the node and fail with the exception you describe.
Any amount of checking for the presence of the child before calling removeChild
in your onfocus handler will be fruitless, since those checks will happen before the onblur handler is triggered.
Apart from re-arranging your event handling and node modifications, your best bet is probably to just handle the exception in a try catch block.
The following code will show how the onblur event handler runs before removeChild
in onfocus actually removes the child. It is also on jsfiddle
html
<div id="iParent">
<input id="i">
</div>
js
var input = document.querySelector("#i"),
inputParent = document.querySelector('#iParent');
input.onblur = function() {
console.log('onblur : input ' + (input.parentNode ? 'has' : 'doesnt have')
+ ' a parent BEFORE delete');
try {
inputParent.removeChild(input);
} catch (err) {
console.log('onblur : removeChild failed, input '
+ (input.parentNode ? 'has' : 'doesnt have') + ' a parent');
return false;
}
console.log('onblur : child removed');
};
input.onfocus = function() {
console.log('onfocus : input ' + (input.parentNode ? 'has' : 'doesnt have')
+ ' a parent BEFORE delete');
try {
inputParent.removeChild(input);
} catch (err) {
console.log('onfocus : removeChild failed, input '
+ (input.parentNode ? 'has' : 'doesnt have') + ' a parent');
return false;
}
console.log('onfocus : child removed');
};
Console output after focusing on the input field will be
onfocus : input has a parent BEFORE delete
onblur : input has a parent BEFORE delete
onblur : child removed
onfocus : removeChild failed, input doesnt have a parent
Library
? Because when I tried "what I think it is", it worked? – Buncombe