How get element by data-attribute in javasript?

I have this data-attribute How better interact with this element console.log(document.querySelector("dropdown[aria-current]")) returns null I'm use react - any ideas how do it better with react? SOLUTION
const dropdownItem = document.querySelector(".dropdown-item[aria-current]");
if (dropdownItem) {
dropdownItem.addEventListener("onmouseleave", returnActive)
}
const dropdownItem = document.querySelector(".dropdown-item[aria-current]");
if (dropdownItem) {
dropdownItem.addEventListener("onmouseleave", returnActive)
}
14 Replies
Jochem
Jochem•2y ago
it's not a dropdown element, you're missing the . to make it a class selector also, even then, I don't see the dropdown class, just .dropdown-item, so .dropdown-item[aria-current] should work as a selector
Nikita
NikitaOP•2y ago
Its was so simple
Nikita
NikitaOP•2y ago
I got next error - cna you help please? If I check it like this its also doesn't help
if (document.querySelector(".dropdown-item[aria-current]")) {

document.querySelector(".dropdown-item[aria-current]").addEventListener("onmouseleave", returnActive)
}
if (document.querySelector(".dropdown-item[aria-current]")) {

document.querySelector(".dropdown-item[aria-current]").addEventListener("onmouseleave", returnActive)
}
Jochem
Jochem•2y ago
what's the error? wait, nm, missed the screenshot
Nikita
NikitaOP•2y ago
Object is possibly 'null'
Jochem
Jochem•2y ago
const dropdownItem = document.querySelector(".dropdown-item[aria-current]");
if (dropdownItem) {
dropdownItem.addEventListener("onmouseleave", returnActive)
}
const dropdownItem = document.querySelector(".dropdown-item[aria-current]");
if (dropdownItem) {
dropdownItem.addEventListener("onmouseleave", returnActive)
}
sorry, forgot a bit before sending
Nikita
NikitaOP•2y ago
Now it works fine
Nikita
NikitaOP•2y ago
Thank you
Jochem
Jochem•2y ago
np 🙂 The reason typescript was doing that, is that it doesn't actually understand what querySelector does, beyond take a string and return either null or an HTMLElement. It can't know that running it twice (once in the if, then again just below) will yield the same result, so it defaults back to checking the return signature. The code was valid, and wouldn't have ever produced an error unless there's a really weird situation where something else deletes the element between the if and addEventListener calls
Nikita
NikitaOP•2y ago
@jochemm may I ask you in this thread - what to do if function doesn't work
Nikita
NikitaOP•2y ago
I mean I got no console.log
Jochem
Jochem•2y ago
ah! I missed that copying your code, the vanilla event is called mouseleave, no on
Nikita
NikitaOP•2y ago
now it works thank you again!
Jochem
Jochem•2y ago
no worries 😄

Did you find this page helpful?