2

I seem to have a problem accessing a childnode's childnode, without doing it in a very ineffective way.

Say I have this HTML:

<div class="parent">
    <div class="child">
        <div class="childIWantToGet">
        </div>
    </div>
</div>

I've tried this in JS:

parent.childNodes[0].childNodes[0]

.. And it's not very effective if I have to access a childnode, say 10 levels down.

I did try:

parent.closest(".childIWantToGet");

..But this return null.

Am I missing something very obvious here?

Sorry if this question have been asked before. I have been looking for quite a time for an answer now.

Thanks in advance.

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
Guttulsrud
  • 51
  • 4
  • 2
    Closest is for finding parents, and it is a jquery function. The quickest way is using "find" function of jquery. – pabgaran Jun 04 '19 at 16:58
  • 1
    @pabgaran _"...and it is a jquery function"_ Not anymore ;) -> [`Element.closest()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest) – Andreas Jun 04 '19 at 17:00
  • in vanilla js: https://stackoverflow.com/questions/16302045/finding-child-element-of-parent-pure-javascript/16302110 – GrafiCode Jun 04 '19 at 17:00
  • 2
    Well, if you know the class (or some other attribute you can select with) you can use `querySelector` on the parent: `parent.querySelector('.childIWantToGet')` – chazsolo Jun 04 '19 at 17:00
  • @Andreas but it is not standard, it does not work in all browsers. – pabgaran Jun 04 '19 at 17:02
  • 2
    @pabgaran _"not standard"_? o.O It works in all but IE (and [IE isn't a browser](https://techcommunity.microsoft.com/t5/Windows-IT-Pro-Blog/The-perils-of-using-Internet-Explorer-as-your-default-browser/ba-p/331732)) : https://developer.mozilla.org/en-US/docs/Web/API/Element/closest – Andreas Jun 04 '19 at 17:03
  • @Andreas ok, you are damn right. – pabgaran Jun 04 '19 at 17:05
  • @pabgaran Are all classes the same for each level? Are they unique for each level? Are they all divs? – zer00ne Jun 04 '19 at 17:06

0 Answers0