TypeError document.querySelector(...) is null

16,101

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
}
Share:
16,101
Jase Pellerin
Author by

Jase Pellerin

I have a lot of random skills. I'll try to help you understand your coding issues if you do the same for me! Let's make the world of coding a little less confusing. Feel free to message me personally if you need anything at all!

Updated on June 13, 2022

Comments

  • Jase Pellerin
    Jase Pellerin almost 2 years

    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);
    }