S
S
Shimpanze2018-02-04 14:17:55
JavaScript
Shimpanze, 2018-02-04 14:17:55

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

2 answer(s)
I
Ivan Bogachev, 2018-02-04
@Shimpanze

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.

A
Alexander, 2018-02-04
@alexr64

Because there is no second element in the matches array now.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question