admin管理员组

文章数量:1289527

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) { // .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'] : "/";
	$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>

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./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/";
	$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>

Share Improve this question edited Nov 14, 2019 at 18:42 Barmar 782k56 gold badges546 silver badges660 bronze badges asked Nov 14, 2019 at 18:29 Braheem Hazeem Grumpy WolfBraheem Hazeem Grumpy Wolf 111 gold badge1 silver badge2 bronze badges 5
  • Which line is getting the error? – Barmar Commented Nov 14, 2019 at 18:35
  • 1 There is nothing we can do to salvage this dump of code. Please a) remove the PHP if this is a JS question, replace the echo with real stuff. and b) Fix your quotes here id=urlBox"> Please look at How to Ask and create a minimal reproducible example using the [<>] snippet editor the way it was designed – mplungjan Commented Nov 14, 2019 at 18:37
  • Your submit only console.log s the url entered instead of calling the php to read the url from the net – mplungjan Commented Nov 14, 2019 at 18:39
  • Can you explain what all that JavaScript is doing? It seems to be rebuilding the DOM after it's loaded, maybe it's not copying the elements that you want to add listeners to. – Barmar Commented Nov 14, 2019 at 18:44
  • You should also add your stack trace if possible. – Akin Okegbile Commented Nov 14, 2019 at 21:03
Add a ment  | 

6 Answers 6

Reset to default 4

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 remended though).

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

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

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

Good luck! ~E

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.

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) {

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!

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

本文标签: javascriptUncaught TypeError Cannot read property addEventListener of nullStack Overflow