1

I have a <div> set up that I want to add/remove using a Firestore listener. All my documents in my collection have a unique Firestore-generated ID.

The user can press the X button on the element to remove that element from the database whilst also removing it from the frontend.

Everything works, HOWEVER whilst testing I noticed that SOMETIMES

Uncaught DOMException: Failed to execute 'querySelector' on 'Element': '[data-id = 9NrmaFNNBX1DrH940osh]' is not a valid selector.

It works perfectly fine but just randomly (or so I feel since it works half the time but out of the blue just throws me that error).

The code associated with that error message is this:

if (book.type ==="removed") {
    let removedCard = mainContent.querySelector(`[data-id = ${uniqueID}]`);
    mainContent.removeChild(removedCard);
}

When I refresh, it works perfectly fine on the same element. But especially after deleting multiple elements in a row it happens almost 100%.

samthecodingman
  • 23,122
  • 4
  • 30
  • 54
Duke Kim
  • 43
  • 5

1 Answers1

1

I think that the reason why this is happening randomly is because of how the querySelector works in JavaScript. According to this SO Overflow question and the querySelector docs, querySelector uses CSS selectors to grab the elements on the DOM, which can't start with digits.

Looking at your ID there, 9NrmaFNNBX1DrH940osh, and knowing that Firebase (usually) generates these ID's with random strings and digits, you're probably just running into issues where some Firebase ID's start with a digit, and others start with letters, which would make them valid.

One potential solution that I can think of for this, that I've done in the past, is to combine another attribute of your item in the database, with that ID, and use that as the data-id attribute. That way, they always start with letters and will always be valid. For example, something like:

function itemId(item) { // item here is your firebase document
  return `${item.name}-${item.id}`
}

And use that value inside of your HTML instead.

Another (easier) solution thanks to @samthecodingman: you can also prefix id- to your data-id attribute in front of the Firestore document ID, and that would also make this CSS selector valid.

Otter
  • 240
  • 2
  • 11
  • 1
    I'd argue it's just simpler to prefix with a single underscore `_` or some standard static string like `id-`, then if you need to do something with the ID, you know what you need to trim from it. – samthecodingman Apr 30 '21 at 14:57
  • Oh yeah, that's probably a lot easier. Good idea – Otter Apr 30 '21 at 16:35
  • That worked beautifully. Thanks guys! probs shoulda noticed but that just went over my head. – Duke Kim May 01 '21 at 09:08