The reference at https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll mentions that the selector that you pass must be a valid CSS selector. In fact, if you look at the full error generated by your code, it gives the following:
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '.usuggest li[aria-selected!='true']' is not a valid selector.
Telling us that there is an issue with the selector.
Moving to the CSS selectors at https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors and attribute selectors at https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors, we see that to select an attribute, !=
is not a valid operator. From Can't find a "not equal" css attribute selector we can then see that we would need to prepend with :not
to apply the inverse and then do an equality check.
This gives us the following updated JavaScript
document.querySelectorAll(".usuggest li:not([aria-selected='true'])")
Which should do what you want.
This then makes the entire query:
document.querySelectorAll(".usuggest li:not([aria-selected='true'])")[0].setAttribute('aria-selected', 'true');
Since the querySelectorAll
may not return results, I would recommend doing the following:
const falseListItems = document.querySelectorAll(".usuggest li:not([aria-selected='true'])");
if (falseListItems.length > 0) {
falseListItems[0].setAttribute('aria-selected', 'true');
}
If you can guarantee that the query will lead to a single result, then the extra if statement is not necessary of course.