I was checking if some elements exist with:
if ($(selector).length > 0){
....
}
However, sometimes the returned object (even if the element exists in the DOM and has returned) does not have the length attribute so this never evaluates to true. This error appears in chrome. Do you have any idea what the problem might be?
Edit: I use this code:
var variable;
for(let elem in selectors){
if($(elem).length > 0){
variable = true;
break;
}
else
variable = false;
}
Given a list of selectors, variable is true if at least one of the selectors exists. This is inside a google chrome extension's content script. After this code runs in the plugin I get the same problem even in the console of google chrome.
Edit: This code does not create a problem:
var variable;
if($(elem).length > 0){
variable = true;
}
else
variable = false;
It seams that the problem is the for loop or/and the break; statement. However, a for loop is needed to make this code work for a list of selectors and not just for one.
It seams that the document.querySelectorAll() does not create the same problem and works as expected. So I used this one instead of the $(). If you only want to check if an element exists it is working just fine.
So this code always returns true if at least one of the selectors exists in the web page:
function exists(selectors){
var selectorExists = false;
for(let i=0; i < selectors.length; i++){
let element = document.querySelectorAll(selectors[i]);
if(element.length > 0){
selectorExists = true;
break;
}
}
return selectorExists;
}
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