Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError document.querySelector(...) is null

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);
}
like image 330
Jase Pellerin Avatar asked Dec 03 '14 14:12

Jase Pellerin


People also ask

Why is document querySelector null?

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

How do you querySelector in react?

querySelector() method in React is using refs. To select an element, set the ref prop on it to the return value of calling the useRef() hook and access the dom element using the current property on the ref , e.g. ref. current . Copied!

Should I use querySelector or getElementById?

You should opt to use the querySelector method if you need to select elements using more complex rules that are easily represented using a CSS selector. If you want to select an element by its ID, using getElementById is a good choice.


1 Answers

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
}
like image 139
Amit Joki Avatar answered Sep 28 '22 01:09

Amit Joki