14

I need to get all the direct children of an element. As it is here:

<div class='1'>
    <div class='2'>
        <div class='3'></div>
    </div>
    <div class='2'></div>
</div>

I need the two DIVs with class "2" using the one with class "1". Plain JavaScript - no libraries.

(They are the same class in this example just to be more clear. In my need they are with different, unknown classes.)

Krupp
  • 351
  • 1
  • 5
  • 18

1 Answers1

24

One option is to use the direct child combinator, >, and the universal selector, *, in order to select direct children elements of any type:

document.querySelectorAll('.element > *');

Alternatively, there is also a .children property that will return all the direct children elements:

document.querySelector('.element').children;
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • 1
    don't seem to get that working... i don't either want the task to be havy for the CPU. So my question - will it be a problem if i use `menuitem` or `aside` or some other tag instead of the `div` with class "3"? – Krupp Jan 24 '16 at 03:09
  • 8
    There is nothing CPU-intensive about that operation. It's literally just a check for whether each element's parent has `.element` class. – BoltClock Jan 24 '16 at 05:40
  • @BoltClock While it is definitely a micro-optimization, the * selector should be used cautiously. Using `*` means you need to consider _every_ element before ending its search. You can probably get away with it in most cases, but it wouldn't be a good idea to run in an animation loop, for example. – elliottregan Dec 30 '18 at 03:36
  • @elliottregan - In general, you will *not* run into noticeable performance issues purely based on the CSS selectors that you use. All modern browsers are optimized to select elements efficiently. If you run into performance issues, the culprit is almost always going to be an operation other than the selector. Also, here is a [quick example](http://jsfiddle.net/e9prgaof/) where 1k elements are selected with the universal selector and then manipulated every second... you can easily run this for 10k elements without a problem... – Josh Crozier Dec 30 '18 at 04:18
  • 1
    @elliottregan: Yeah, it's not the selector itself that's expensive but the fact that it scales with the number of elements on the page when appearing at the end of a selector, and by using it you are potentially doing much more work than necessary. – BoltClock Dec 30 '18 at 04:20