javascript - How to make a selector for direct child of the root node? - Stack Overflow

Consider that you are given a node node and you must provide all direct children given by selector Dire

Consider that you are given a node node and you must provide all direct children given by selector Direct. Selector for direct child is:

childParent > directChild

However, the following fails with an error in console:

document.body.querySelectorAll(">div")
SyntaxError: '>div' is not a valid selector

I have a function that needs to do something on select direct child nodes, but I'm not sure how to handle this. Except of course using the for loop and analyse the children with my own code, abandoning selectors pletely.

The following code does not work. Can it be changed so that it does what is intended?

function doWithDirectChildren(parentNode) {
    // does not work, the selector is invalid
    const children = parentNode.querySelector(">.shouldBeAffected");
    for(const direct of children) {
        // do something with the direct child
    }
}

I'm asking for a solution, not a workaround.

Consider that you are given a node node and you must provide all direct children given by selector Direct. Selector for direct child is:

childParent > directChild

However, the following fails with an error in console:

document.body.querySelectorAll(">div")
SyntaxError: '>div' is not a valid selector

I have a function that needs to do something on select direct child nodes, but I'm not sure how to handle this. Except of course using the for loop and analyse the children with my own code, abandoning selectors pletely.

The following code does not work. Can it be changed so that it does what is intended?

function doWithDirectChildren(parentNode) {
    // does not work, the selector is invalid
    const children = parentNode.querySelector(">.shouldBeAffected");
    for(const direct of children) {
        // do something with the direct child
    }
}

I'm asking for a solution, not a workaround.

Share Improve this question asked Jan 9, 2020 at 17:49 Tomáš ZatoTomáš Zato 53.5k63 gold badges310 silver badges828 bronze badges 7
  • What is the root node? body? – Ori Drori Commented Jan 9, 2020 at 17:51
  • 3 If it's always body you can do document.querySelectorAll('body > div') – JJWesterkamp Commented Jan 9, 2020 at 17:51
  • jQuery solves this problem api.jquery./children – TKoL Commented Jan 9, 2020 at 17:56
  • jsfiddle/xs7eb81h – TKoL Commented Jan 9, 2020 at 17:57
  • Without including jQuery, I'd say @JeffreyWesterkamp 's ment is the way to go. – Taplar Commented Jan 9, 2020 at 18:03
 |  Show 2 more ments

3 Answers 3

Reset to default 10

The proper way to do this is with the :scope psuedo class.

According to the documentation at MDN:

When used from a DOM API such as querySelector(), querySelectorAll(), matches(), or Element.closest(), :scope matches the element on which the method was called.

For example:

let parent = document.querySelector('#parent');
let scoped = parent.querySelectorAll(':scope > span');

Array.from(scoped).forEach(s => {
  s.classList.add('selected');
});
.selected {
  background: yellow;
}
<div id="parent">
  <span> Select Me </span> <br>
  <span> Me Too </span>
</div>
<span> Not Selected </span>

The child binator operator > is a binary operator so using it with nothing on the left side is invalid.

The child binator (>) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first.

If you can provide individual parent and child selectors you can do something simple like this

let directChildren = (parent, child) => document.querySelectorAll(`${parent} > ${child}`);
directChildren('body','div');//...

If your parent argument is a node or collection you would have to use a method of converting it back to a selector, like this one

jQuery solves this problem in 2 ways. Consider this code:

$('div.root').find('> .p2').addClass('highlighted');
$('div.root').children('.p2').addClass('red');
.highlighted {
  background: yellow
}

.red {
  color: red
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="root">
  <p>div 1</p>
  <p class="p2">paragraph 2</p>
  <p>paragraph 3</p>
  
  <div>
    <p class="p2">paragraph 2 2</p>
  </div>
</div>

using .find('> selector) finds only direct children matching the selector, and using .children('selector') also does the same.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744276514a4566356.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信