简体   繁体   中英

JavaScript code is not executed during the runtime of the code, but when I debug it and execute in console, it works

I have a following code:

var e = document.getElementById("overlay");
e.parentNode.removeChild(e);

This code is supposed to remove the DOM element, but it doesn't. So I removed the code and added a breakpoint in its stead and input the code in the console during the pause manually, and it worked (ie the element was successfully removed).

This behavior seems rather strange for me, so I wanted to ask, why does it happen and what can I do to inspect this peculiar issue?

Thanks in advance.

EDIT: Thanks for quick replies. Nonetheless, I want to make it perfectly clear that the element #overlay does exist at the time of the execution of the code. Moreover, when I put a debugging breakpoint at that place in the code and execute these two lines of code, it does have an effect on this particular existent element (which it doesn't without debugging).

EDIT 2: I was asked to clarify the code. I execute the following code before the body (part of the queryloader2 plugin, which ensures image preloading):

window.addEventListener('DOMContentLoaded', function() {
    new QueryLoader2(document.querySelector("body"), {});
});

No errors present (except for a 404 error because of missing image, which has no impact on Javascript).

As Teemu mentioned #overlay more than likely doesn't exist when the code is run.

For a test.. Try wrapping your code in either of these...

Javscript

window.onload = function () { /*your code*/ };

Jquery (if included)

$(document).ready(function () { /* your code*/ });

You should execute your code after the DOM tree has finished loading. One option is to wrap your code in a function that executes after the DOMContentLoaded event has been fired.

document.addEventListener("DOMContentLoaded", function(event) { 
  // your code
});

Look at this answer for more information: $(document).ready equivalent without jQuery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM