Icezua
Icezua

Reputation: 35

Uncaught TypeError: Cannot read properties of null (reading 'style')

I, trying to make a div clickable so it will be redirected to a different document or site but got that error. However, it works with the old way of using the onclick as an attribute inside the element.

var examscol = document.getElementById("exam-col1");
function examCol() {
  return window.location.assign("https://www.w3schools.com")
}

examscol.addEventListener("click", examCol);

Any suggestions on why it isn't working with this way ?

Upvotes: 2

Views: 3736

Answers (2)

Sercan
Sercan

Reputation: 5101

1. Problem

The problem is that the id of the element is not exam-col1. When I change the id of the element to exam-col I get the following error [1]:

Error
{
  "message": "Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')",
}
2. Hint

The frame cannot be displayed when the URL's X-Frame-Options field is set to SAMEORIGIN. The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe>, <embed> or <object> [2]. That's why I changed the targeted URL.

/* If there is no item with an id of "exam-col1" on the page, you will get a "null" error. */
var examscol = document.getElementById("exam-col1");

function examCol() {
 return window.location.assign("https://www.wikipedia.com")
}

examscol.addEventListener("click", examCol);
.clickable {
  display: inline;
  cursor: pointer;
  padding: 5px;
  border: 1px solid red;
}
<!-- Note that the id of the item is "exam-col1". -->
<div id="exam-col1" class="clickable">Open</div>


1 - JavaScript TypeError: Cannot read property 'style' of null
2 - X-Frame-Options

Upvotes: 1

Zeeshan
Zeeshan

Reputation: 184

I thinks nothing wrong in this code it something else referring to some style error .you can check your html if its ok and also show you code to insure whats the problem. Its would be pleasure

Upvotes: 1

Related Questions