Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I wrote a Chrome plugin, and I am listening to the 'DOM ready event' like this:

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

Sometimes I cannot get the elements I want, even if they really exist. But when the page is loaded, I open the developer tools and run the same code in console and it works again.

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

like image 603
Dorsey Avatar asked Jul 22 '12 14:07

Dorsey


2 Answers

Sounds like the elements you are looking for are being added after the DOM is ready.

Try swaping out your document.ready for the function 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 to execute code and attach event handlers: $(document).ready and $(window).load. The document ready event executes already when the HTML-Document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet. If you want to hook up your events for certain elements before the window loads, then $(document).ready is the right place.

The window load event executes a bit later when the complete page is fully loaded, including all frames, objects and images. Therefore functions which concern images or other page contents should 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/

like image 128
TheAlbear Avatar answered Nov 04 '22 00:11

TheAlbear


If the DOM is really ready and the elements aren't being added later by other code, they will be there to be found. If you're not finding them, it suggests a problem with the selector(s) you're using, or it suggests they're being added by other code (rather than being in the markup).

like image 31
T.J. Crowder Avatar answered Nov 04 '22 00:11

T.J. Crowder