I'm having some difficulty here with getElementById returning a null object. All of the below code has been placed inside an anonymous function that is called when "DOMContentLoaded" (event listener). I did this to avoid getElementById not being able to find the twitter button when I attempt to set an attribute (particularly "data-text"). The first function has no problem locating the element (an 'a' element on the page) with getElementById, but the second function returns null. I thought that running it only after "DOMContentLoaded" would solve this problem? What am I missing here? (please let me know if I'm not putting enough of my code here to show what I'm trying to do.)
//Add initial invisible quote
(function () {
var quoteList = document.querySelector(".hidden-quotes").children;
var randomQuoteNum = Math.round((Math.random() * (quoteList.length - 1)));
var quoteBox = document.getElementById("quote-box");
quoteBox.innerHTML = quoteList[randomQuoteNum].innerHTML;
var tweetQuote = (quoteBox.children[0].innerHTML + " " + quoteBox.children[1].innerHTML);
var tweetButton = document.getElementById("tweet-button");
tweetButton.setAttribute("data-text", tweetQuote);
tweetButton.setAttribute("data-url", " ");
})();
//Set up quote button functionality
var magicButton = document.getElementById("quote-button");
magicButton.addEventListener("click", function () {
var quoteList = document.querySelector(".hidden-quotes").children;
var randomQuoteNum = Math.round((Math.random() * (quoteList.length - 1)));
var quoteBox = document.getElementById("quote-box");
quoteBox.innerHTML = quoteList[randomQuoteNum].innerHTML;
var tweetQuote = (quoteBox.children[0].innerHTML + " " + quoteBox.children[1].innerHTML);
var tweetButton = document.getElementById("tweet-button");
console.log(tweetButton);
tweetButton.setAttribute("data-text", tweetQuote);
quoteBox.style.opacity = 1;
});
Here's the markup:
<a id="tweet-button" class="twitter-share-button" href="https://twitter.com/intent/tweet">Tweet this.</a>
Only the first function seems to be able to access and modify an attribute of the above element, while the second function cannot even find it (getDocumentById returns null).