Answer the question
In order to leave comments, you need to log in
JavaScript: What causes the error: Uncaught TypeError: Cannot read property '1' of null?
Good afternoon!
Can you please tell me what is causing the error: Uncaught TypeError: Cannot read property '1' of null?
var as = document.getElementsByTagName('a');
var re = /^https?:\/\/([^\/]*)\//;
for (var i = 0, l = as.length; i < l; i++) {
var href = as[i].href;
var matches = href.match(re);
if (matches[1] && matches[1] != "mysite") {
as[i].setAttribute("target","_blank");
}
}
Answer the question
In order to leave comments, you need to log in
The error occurs because the matches variable is null. Most likely one of the links has a curved href. Accordingly, match(...) does not find matches and returns null. Before using the result of this method, check what it returned.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question