anoop chandran anoop chandran - 1 year ago 66
Javascript Question

Get innerHTML after the page loads completely

I'm attempting a make random quote machine with a tweet button to tweet the quote.
The random quote is coming up just fine.
The code..

var forismaticAPI = '';
$(document).ready(function() {
var template = function(data) {
$('#quotearea').append('<blockquote id="quote">' + data.quoteText + '</blockquote>' + '<p id="author"> — ' + data.quoteAuthor + '</p>');

var dataAppend = function() {
$.getJSON(forismaticAPI, template);

My next task is to get the quote content to be tweeted. So once the window loads completely i want to get the innerHTML of
which contains the quote. So i write a window.onload function like this..

window.onload = function(){
var quote = document.getElementById('quote');


But I'm getting an error
Uncaught TypeError: Cannot read property 'innerHTML' of null(…)
.. Since there is small delay in loading the quote, the window load function returns a null. How to get the innerHTML of a div only when the content is loaded and ready?

Answer Source

Your #quote element is created after the window.onload event, because it's only created on the return of your ajax call. Move the code from onload to success of the ajax call, as BlueBoy suggested in comments. In your case, the success function is the one you named template.

You can access your element immediately after creating it:

var template = function(data) {
    $('#quotearea').append('<blockquote id="quote">' + data.quoteText 
    + '</blockquote>' + '<p id="author"> —  ' + data.quoteAuthor + '</p>');


You can't call the innerHTML method on DOM elements that do not exist yet. So the first moment you can run your function is after the append() call, which is creating a DOM element with and id of quote.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download