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);
}
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.
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!
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With