user944513
user944513

Reputation: 12729

DOMException: Failed to execute 'querySelectorAll' on 'Document': '.u28suggest li:first a' is not a valid selector

I am trying to execute this line and getting below error

if (document.querySelectorAll('.u28suggest li:first a').length > 0) {

Error:

DOMException: Failed to execute 'querySelectorAll' on 'Document': '.u28suggest li:first a' is not a valid selector.

How can I fix this?

Upvotes: 0

Views: 2142

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

As the error message is telling you, that's not a valid selector, specifically the :first part, which is a jQuery-only thing, not CSS. The equivalent to what that would mean in jQuery using the DOM and CSS is:

// Get the first match for `.u28suggest li`
const li = document.querySelector(".u28suggest li");
// If we got one and it has at least one `a` in it...
if (li && li.querySelectorAll("a").length > 0) {

Or with optional chaining, since undefined > 0 is false:

if (document.querySelector(".u28suggest li")?.querySelectorAll("a").length > 0) {

Just beware that you always need to consider what the result will be when the left-hand side evaluates to undefined. Again, undefined > 0 is false here and that's what we want, but it can bite you. :-)

Upvotes: 2

Related Questions