In html i have this:
<div id="1" onclick="functionX()"> </div>
<div id="2" onclick="functionX()"> </div>
And my script:
functionX() {
if (document.getElementById("1").hasAttribute("onclick")) {
window.onclick = e => {
document.getElementById(e.target.id).appendChild(document.createElement("div", {
class: "someClass"
}));
}
}
}
if (document.getElementById("1").contains(document.getElementById("1").querySelector("[class='someClass']")))
{
let foo = document.getElementsByClassName('myClass');
for (let i = 0; i < foo.length; i )
{
foo[i].removeAttribute("onclick");
}
}
When i click on the div which no longer has an attribute "onclick" the condition from the functionX continues to execute.
CodePudding user response:
The thing is you're removing an attribute. Removing the attribute does nothing to remove the event handler. You need to detach the handler.
CodePudding user response:
The if is not part of the function.
functionX() {
if (document.getElementById("1").hasAttribute("onclick")) {
window.onclick = e => {
document.getElementById(e.target.id).appendChild(document.createElement("div", {
class: "someClass"
}));
}
}
} // end of function
// not in fuction
if (document.getElementById("1").contains(document.getElementById("1").querySelector("[class='someClass']"))) {
let foo = document.getElementsByClassName('myClass');
for (let i = 0; i < foo.length; i ) {
foo[i].removeAttribute("onclick");
}
}