1

My goal is to check if an element exists, but not just that, the element is.. well let me show you: if(document.getElementsByClassName("outerBox").getElementsByClassName("innerBox")) {//some code}. Now the problem is that if outerBox doesnt exist, it gives me this error message in the console: Uncaught TypeError: Cannot read property 'getElementsByClassName' of undefined.

I do not care weather the outerBox exists if it doesn't have the innerBox as a child, and also I do not care if the innerBox exsists outside of the outerBox. They have to be child and parent to eachother.

The code works, but I would like to get rid of the error, for a cleaner expirience, and because it isn't a good practise to leave errors displaying around like that, specially because you can't really use the console while this error is going, because the code is run every 100 milliseconds, so it just spams the console like crazy.

  • Now jsut one last thing, I can't use any outside library like jQuery, only vanilla Javascript.
Tobias H.
  • 426
  • 1
  • 6
  • 18
  • 1
    Try optional chaining `if(document.getElementsByClassName("outerBox")?.getElementsByClassName("innerBox")) {//some code}` (that ? before .) – Dominik Matis Feb 26 '21 at 21:20

1 Answers1

3

Just use querySelector instead:

if (document.querySelector('.outerBox > .innerBox')) {
  // then an innerBox exists as a direct child of an outerBox
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 2
    Not only is it cleaner, it's [faster than `getElementByClassName`](https://stackoverflow.com/a/54952474/14956277) when you're interacting with the results. – D M Feb 26 '21 at 21:21
  • How would you do this if the element had to be say nr. 2, like document.getElementsByClassName("outerBox")[1]? – Tobias H. Feb 26 '21 at 21:25
  • Without knowing more about the HTML structure, optional chaining after `document.querySelectorAll('.outerBox')[2]` but with the HTML you might be able to do something with `nth-child` – CertainPerformance Feb 26 '21 at 21:28