anoop chandran anoop chandran - 5 days ago 7
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 = 'http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=?';
$(document).ready(function() {
var template = function(data) {
$('#quotearea').empty();
$('#quotearea').append('<blockquote id="quote">' + data.quoteText + '</blockquote>' + '<p id="author"> — ' + data.quoteAuthor + '</p>');
$('#quotearea').show();
};

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
#quote
which contains the quote. So i write a window.onload function like this..

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

}


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

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').empty();
    $('#quotearea').append('<blockquote id="quote">' + data.quoteText 
    + '</blockquote>' + '<p id="author"> —  ' + data.quoteAuthor + '</p>');
    $('#quotearea').show();

    console.log(document.getElementById('quote'));
};

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.

Comments