TypeError document.querySelector(...) is null

Jase Pellerin picture Jase Pellerin · Dec 3, 2014 · Viewed 11.8k times · Source

I'm making a FF extension and I hit a snag. Here's what I have:

var canLink = document.querySelector('link[rel="service"]').href;

This finds a link with rel="service" and it works great. However, if the page does not have a link with rel=service, it returns null and breaks out of the rest of the program. How can I make it so that if canLink = null, it doesn't break?

Is there a way to catch this error?

Here is the file. Line 12 is self.port.emit, which works fine.

//Get link if it exists
var elem = document.querySelector('link[rel="service"]').href,
canLink = elem ? elem.href : "";

if (canLink){
    self.port.emit("link", canLink);
}

else {
        canLink = "";
        self.port.emit("link", canLink);
}

Answer

Amit Joki picture Amit Joki · Dec 3, 2014

Use a simple condition

var elem = document.querySelector('link[rel="service"]');
var canLink = elem ? elem.href : "";

Now in your code you could check in your code for "" (empty string) and take further measures like

if(canLink !== "") {  // could be just written as if(canLink){ ... }
   // do something with the canLink now
}