3

How can I get a Node's only direct children with a specific class name?

Example

<div class="list-group">
  <div class="list-group-item">
    <div class="list-group"> <!--I have this-->
      <div class="list-group-item"> <!--And I want to reach this-->
        <div class="list-group">
          <div class="list-group-item"></div> <!--Not this-->
          <div class="list-group-item"></div>
        </div>
      </div>
      <div class="list-group-item"></div> <!--And get this-->
    </div>
  </div>
</div>

I have a list-group that contains items and groups and I want to keep that hierarchy and get a list-group's only direct list-group-items.

How can I do so?

CroMagnon
  • 1,218
  • 7
  • 20
  • 32
Kreator
  • 59
  • 1
  • 11
  • Add Your current selector. – Maciej Sikora Jan 03 '17 at 08:49
  • this question may have been answered in this [post](https://stackoverflow.com/q/3680876/5409815) using the `:scope` pseudo class. See [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/:scope#direct_children) for more info. – lochiwei Sep 11 '21 at 02:07

3 Answers3

3

You haven't mentioned if you use any JS frameworks, but with JQuery it is fairly simple... just use children()

In example $("#haveThis").children()

You can also filter children like: $("#haveThis").children("list-group-item")

docs: https://api.jquery.com/children/

For vanilla JS I'd do this:

[].slice.call(document.getElementById("havethis").children).filter(el=>el.className==='list-group-item')
Mirko Vukušić
  • 2,091
  • 1
  • 10
  • 14
  • Edit : I know about the JQuery solution but I didn't know I could use JQuery functions on var Node like $(Node).children – Kreator Jan 03 '17 at 10:03
  • If you don't target IE or Opera Mini, it's pretty safe to use `Array.from` instead of `[].slice.call`. – fodma1 Mar 22 '18 at 05:35
0

In vanilla JS (if you're not using jQuery) element.children (where element is the parent you wish to query) will return a list of all direct child nodes, you would then itterate over the list list, looking for node.className = "list-group-item"; I've not found a way to do this with standard CSS selectors, so a coded solution seems to be the only option.

allnodcoms
  • 1,244
  • 10
  • 14
-3

Get all elements with the specified class name:

var x = document.getElementsByClassName("list-group-item");

Link https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

digit
  • 4,479
  • 3
  • 24
  • 43