Can't access elements with document.ready from the DOM using jQuery?

I wrote a Chrome plugin and I listen to the "DOM ready event" as follows:

$(document).ready(function () { //here I select some elements and remove them. }); 

Sometimes I can’t get the elements I need, even if they really exist. But when the page loads, I open the developer tools and run the same code in the console, and it works again.

I am confused why I cannot get the elements when the DOM is ready, and the code I write is correct.

+4
source share
2 answers

It looks like the items you are looking for are added after the DOM is ready.

Try changing your document to the document below.

 $(window).load(function() { // executes when complete page is fully loaded, including all frames, objects and images alert("window is loaded"); }); 

jQuery offers two powerful methods for executing code and attaching event handlers: $ (document) .ready and $ (window) .load. A document ready event is already triggered when an HTML document is loaded, and the DOM is ready, even if all image files are not already loaded. If you want to connect events to certain elements before loading the window, then $ (document) .ready is the right place.

The window load event is executed a bit later when the full page is fully loaded, including all frames, objects, and images. Therefore, functions related to images or other page content must be placed in the load event for the window or the content tag itself.

Taken from http://4loc.wordpress.com/2009/04/28/documentready-vs-windowload/

+5
source

If the DOM is really ready, and the elements will not be added later by other code, they will be found. If you do not find them, this indicates a problem with the selector (s) you are using, or suggests that they are added by other code (and not in the markup).

+3
source

All Articles