Uncaught TypeError: Cannot read property addEventListener of null

Im working on an assignment for my javascript class, and I keep getting the error

fetch_page.js:109 Uncaught TypeError: Cannot read property 'addEventListener' of null at addEventListeners (fetch_page.js:109) at fetch_page.js:121

I'll be honost, I don't understand javascript for crap, but I'm forced to take this class for my network admin degree. Can anyone point out where I'm making this error?

window.addEventListener('DOMContentLoaded', (function() {
  var contents;

  var protocol;
  var hostname;
  var directory;
  var file;

  function parseBase() {
    var pos, slashPos;
    var remainder;

    pos = BASE.indexOf('://');
    protocol = BASE.substr(0, pos);
    remainder = BASE.substr(pos + 3);
    slashPos = remainder.indexOf('/');
    if (slashPos === -1) {
      hostname = remainder;
      directory = "";
      file = "";
    } else {
      hostname = remainder.substr(0, slashPos);
      remainder = remainder.substr(slashPos + 1);
      slashPos = remainder.lastIndexOf('/');
      if (slashPos === -1) {
        directory = "";
        file = remainder;
      } else {
        directory = remainder.substr(0, slashPos);
        file = remainder.substr(slashPos + 1);
      }
    }
    console.log("protocol:", protocol);
    console.log("hostname:", hostname);
    console.log("directory:", directory);
    console.log("file:", file);
  }

  function relativeToAbsolute(url) {
    if (url.indexOf('://') > -1) { // http://somedomain.com/path/file.html
      return url;
    } else if (url[0] === '/') { // /path/file.html
      return protocol + "://" + hostname + url;
    } else { // path/file.html
      if (directory === "") {
        return protocol + "://" + hostname + "/" + url;
      } else {
        return protocol + "://" + hostname + "/" + directory + "/" + url;
      }
    }
  }

  function parsePage() {
    var parser = new DOMParser();
    contents = parser.parseFromString(atob(PAGE), "text/html");
    console.log(contents);
  }

  function moveChildren(source, destination) {
    while (source.childNodes.length > 0) {
      var child = source.childNodes[0];
      source.removeChild(child);
      destination.appendChild(child);
    }
  }

  function fixTags(tagName, attribute) {
    var tags = contents.getElementsByTagName(tagName);

    for (var counter = 0; counter < tags.length; counter++) {
      var url = tags[counter].getAttribute(attribute);
      if (url) {
        tags[counter].setAttribute(attribute, relativeToAbsolute(url));
      }
    }
  }

  function fixRedirectedTags(tagName, attribute) {
    var tags = contents.getElementsByTagName(tagName);

    for (var counter = 0; counter < tags.length; counter++) {
      var url = tags[counter].getAttribute(attribute);
      if (url) {
        tags[counter].setAttribute(attribute,
          window.location.origin + window.location.pathname + '?url=' + encodeURIComponent(relativeToAbsolute(url)));

      }
    }
  }

  function fixURLs() {
    fixTags('img', 'src');
    fixTags('script', 'src');
    fixTags('link', 'href');
    fixRedirectedTags('a', 'href');
  }

  function moveContent() {
    moveChildren(contents.head, document.head);
    moveChildren(contents.body, document.getElementById('contents'));
  }

  function submit() {
    console.log("submitted:", encodeURIComponent(document.getElementById('urlBox').value));
  }

  function addEventListeners() {
    document.getElementById('goButton').addEventListener('click', submit);
    document.getElementById('urlBox').addEventListener('keydown', function(event) {
      if (event.keyCode == 13 || event.keyCode == 10) {
        submit();
      }
    });
  }

  return function() {
    parseBase();
    parsePage();
    fixURLs();
    moveContent();
    addEventListeners();
  }
})())
body {
	margin: 0px;
}
#searchBox {
	background: black;
	color: white;
	width: 100%;
	text-align: center;
	vertical-align: middle;
	padding: 10px;
	}
#goButton {
	background: red;
	color: black;
	padding: 4px
	font-weight: bold;
	font-family: Arial;
	font-size: .75em;
	vertical-align: middle;
	cursor: pointer;
}
#urlBox {
	width: 50%
}
#contents {
	border: 1px solid black;
}
<?php
	$url = isset ($_GET['url']) ? $_GET['url'] : "http://eloquentjavascript.net/";
	$contents = base64_encode(mb_convert_encoding(file_get_contents($url), "HTML-ENTITIES","UTF-8"));
	?>
<!doctype html>
<html>
	<head>
		<title>Fetch Page</title>
	<link rel="stylesheet" href="fetch_page.css">
	<script src="fetch_page.js"></script>
	<script>
	var BASE = "<?php echo $url; ?>";
	var PAGE = "<?php echo $contents; ?>";
	</script>
	</head>
	<body>
	<div id="searchBox">Type a URL here: <input type="text" id=urlBox"> <span id="goButton">GO</span></div>
	<div id="tocContainer">
	<div id="toc">[toc goes here]</div>
	<p id="contents">Hello World!</p>
	<div id="contents"></div>
	</body>
	</html>

Upvotes: 1

Views: 15174

Answers (6)

r3tr0vw
r3tr0vw

Reputation: 1

Add window.onload = function() {<enter your javascript code here}; to your script. That easy.

Upvotes: 0

Dickson Anthony
Dickson Anthony

Reputation: 11

I had this problem too and I checked my code and everything was in other. I realized that it was where I positioned my script tag i.e the head of the html file so I then put it at the end of my body tag. I also found out that from one of the guys who answered this question that using "defer" makes it work no matter where the script tag is as long as it's inside the html tag.

Upvotes: 1

Apart from any typing error like eg. omitting quotes, try defer in the <script src ... line of the html code. I solved my problem in this way!

Upvotes: 0

Cherizer
Cherizer

Reputation: 36

Just experienced something similar. Adding a defer to my script tag solved the issue:

<script src="fetch_page.js" defer></script>

Good luck! ~E

Upvotes: 2

FZs
FZs

Reputation: 18619

What does your error mean?

Uncaught TypeError: Cannot read property 'addEventListener' of null. 
     at addEventListeners

That boils down to:

You've tried to access the addEventListener property of something in the addEventListeners function, but that's null.

Take a look at addEventListeners:

document.getElementById('goButton').addEventListener('click', submit);
document.getElementById('urlBox').addEventListener('keydown', function(event) {
    if (event.keyCode == 13 || event.keyCode == 10) {
        submit();
    }
});

One of the getElementsById calls has returned null, indicating that there's no such ID in your code.

After looking at the HTML, you can see that the problem is at the following place:

<input type="text" id=urlBox">

You're missing the opening quote at the ID, so really you've given your element the ID of urlBox" (you can omit quotes around a HTML attribute, but not recommended though).

That's why the JS can't find the element with ID urlBox

Upvotes: 4

ControlAltDel
ControlAltDel

Reputation: 35011

One of these two document.getElementById calls is returning null, because there's no element with that Id. You can add a breakpoint in the debug console in the code, or add a console.log to figure out exactly where the problem is occuring

    document.getElementById('goButton').addEventListener('click', submit);
    document.getElementById('urlBox').addEventListener('keydown', function(event) {

Upvotes: 0

Related Questions