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.

4
  • 2
    Can't you use a css selector and do a querySelector call to check? Commented Sep 3, 2018 at 16:53
  • Like div>:nth-child(2)>:nth-child(1)>:nth-child(2)? Commented Sep 3, 2018 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 + "]"); Commented Sep 3, 2018 at 17:06
  • where possible you should use <element>.querySelector rather than document.querySelector (and use .querySelectorAll if multiple element matches is a possibility) Commented Sep 3, 2018 at 19:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.