0

I'm working on an chrome extension that will optimize some of the Gerrit views in our system. As part of the extension I need to get all the elements with a certain class, say, "gerritBody". When inspecting the page this is what I get: Gerrit Inspection Here's what I tried:

var elems = document.querySelectorAll('#gerrit_body'); // works
var elems = document.querySelectorAll('div#gerrit_body'); // works
var elems = document.getElementsByClassName("gerritBody"); // works (*)
var elems = document.querySelectorAll('.gerritBody'); // doesn't work
var elems = document.querySelectorAll('div.gerritBody'); // doesn't work
var elems = document.querySelectorAll('div#gerrit_body.gerritBody'); // doesn't work

(*) I was okay with using getElementsByClassName(), but for some reason despite me seeing the contents of the returned HTMLCollection, I can't access the elements themselves (elems[0] returns 'undefined').

I tried looking it up but everything I found was about CSS selectors, which I believe I used correctly. I also tried all options with both single and double quotes (I'm really new to JS so no idea if it actually matters).

I would be thankful for any direction on how to debug this - as I mentioned, I'm quite new to it, so I'm at loss right now. Thank you!

Anyuta
  • 21
  • 5
  • 1
    If `getElementsByClassName` "works", and `querySelectorAll` doesn't, you're quering the DOM before the elements exist. (gEBCN returns a live collection, it's updated automatically when the elements are inserted into the DOM.) – Teemu Jan 19 '22 at 14:49
  • @Teemu how do I make sure that the element exists before I query it? Also, why querySelectorAll() works by id then? I thought it had something to do with timing as well, but I cannot for the life of me find a viable explanation as to why it happens. – Anyuta Jan 19 '22 at 14:52
  • Just don't run your script before `body` has been parsed. Usually the script is loaded at the end of the body, that'll make sure all the elements are available. Or use `defer` attribute in the script tag which is placed in `head` section. Also: https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event – Teemu Jan 19 '22 at 14:52

0 Answers0