Barrosy
Barrosy

Reputation: 1457

How could I get a direct child element within JavaScript (without using jQuery)?

Within the following code, I am trying to get all .node elements that are direct child elements of .row elements. Currently my code will look for any given element that matches the .node class within .row element.

How could I get the direct node (e.g. in CSS this would look something like this: .row > .node) in plain JavaScript?

let rows = document.getElementsByClassName("row");
var nodes = [];

for (let i = 0; i < rows.length; i++) {
  console.log(rows[i].getElementsByClassName("node"));
}
.node {
  border-radius: 50%;
  border: 1px solid #000;
}

.node,
.empty {
  display: inline-block;
  height: 50px;
  width: 50px;
  line-height: 50px;
  text-align: center;
}

.d-none {
  display: none;
}
<div class="row">
  <div class="node">
    Foo
  </div>
  <div class="node d-none">
    Foo
  </div>
  <div class="row">
    <div class="empty">
      &nbsp;
    </div>
    <div class="node d-none">
      Foo
    </div>
  </div>
</div>

The problem is that the final .node element (which is nested in like so: .row > .row > .node) will be called for multiple times because I am not addressing it as direct child.

I saw this answer which explains the use of document.querySelector. Should I be using that for the purpose I am trying to reach here? Or Could I achieve the same by just using document.getElementsByClassName?

Upvotes: 0

Views: 996

Answers (2)

Neil Ning
Neil Ning

Reputation: 11

document.querySelector('.row > .node') The selector parameter in querySelector function is the same with CSS/JQuery

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370779

Just use querySelectorAll and use the query string .row > .node:

const nodes = document.querySelectorAll(".row > .node");
nodes.forEach(node => console.log(node.textContent));
.node {
  border-radius: 50%;
  border: 1px solid #000;
}

.node,
.empty {
  display: inline-block;
  height: 50px;
  width: 50px;
  line-height: 50px;
  text-align: center;
}

.d-none {
  display: none;
}
<div class="row">
  <div class="node">
    Foo
  </div>
  <div class="node d-none">
    Foo
  </div>
  <div class="row">
    <div class="empty">
      &nbsp;
    </div>
    <div class="node d-none">
      Foo
    </div>
  </div>
</div>

In almost all cases, a selector string that works to select elements in jQuery will work to select elements with querySelectorAll as well (and to select elements with CSS). (There are a few rare exceptions like :contains, which only have meaning in jQuery.)

Note that you need to use

.row > .node

not

.row < .node

to select .nodes which are children of a .row.

Upvotes: 5

Related Questions