0

My question is pretty much the same as JavaScript, elegant way to check nested object properties for NULL/undefined

however instead of dot notation in dictionaries I need to be able to do the same with dom for example:

div[0].children[1].children[0].children[1]

Now what I COULD do is

if(div[0] && div[0].children[1] && div[0].children[1].children[0]...

but this would make my code blow up. I've tried to use the top voted answer in the linked question but this didn't work once I added the .children in there, it would simply throw false every time. Trying to access it via try/catch does work for the divs that do contain those entries.

Using lodash's get works safely but I don't want to deploy 6kb of this module for something that might get achieved otherwise.

user2330482
  • 1,053
  • 2
  • 11
  • 19
  • 2
    Can't you use a css selector and do a querySelector call to check? – connexo Sep 03 '18 at 16:53
  • Like `div>:nth-child(2)>:nth-child(1)>:nth-child(2)`? – connexo Sep 03 '18 at 16:59
  • Thank you, that might be a good solution but I haven't figured out how to access variables from my JS yet. Running on the SO site: `divOb = document.getElementsByClassName(' js-gps-track nav-links--link')[0]; document.querySelector("[data-name=" + divOb + "]");` – user2330482 Sep 03 '18 at 17:06
  • where possible you should use `.querySelector` rather than `document.querySelector` (and use `.querySelectorAll` if multiple element matches is a possibility) – Alnitak Sep 03 '18 at 19:54

0 Answers0