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•16mo 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
Nikita•16mo ago
Its was so simple
Nikita
Nikita•16mo 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•16mo ago
what's the error? wait, nm, missed the screenshot
Nikita
Nikita•16mo ago
Object is possibly 'null'
Jochem
Jochem•16mo 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
Nikita•16mo ago
Now it works fine
Nikita
Nikita•16mo ago
Thank you
Jochem
Jochem•16mo 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
Nikita•16mo ago
@jochemm may I ask you in this thread - what to do if function doesn't work
Nikita
Nikita•16mo ago
I mean I got no console.log
Jochem
Jochem•16mo ago
ah! I missed that copying your code, the vanilla event is called mouseleave, no on
Nikita
Nikita•16mo ago
now it works thank you again!
Jochem
Jochem•16mo ago
no worries 😄
Want results from more Discord servers?
Add your server