简体   繁体   English

如何递归选择元素Javascript下的所有子项

[英]How to recursively select all children under an element Javascript

I need a function that recursively selects all child elements but wont select elements (and those elements children) if they have the "foo" attribute.我需要一个函数来递归地选择所有子元素,但如果它们具有“foo”属性,则不会选择元素(和那些元素的子元素)。

<section>
  <div>
   <span foo>
    <input>
   </span>
  </div>
  <p>
    <img>
  </p>
</section>
//should return [section, div, p, img]

I need raw Javascript please我需要原始的 Javascript 请

edit: I tried something like this:编辑:我试过这样的事情:

$tag.querySelectorAll(":not([foo])")

but querySelectorAll(":not([foo])") will still return the children of the unselected element.但 querySelectorAll(":not([foo])") 仍将返回未选择元素的子元素。

You can use element.querySelectorAll() with the :not modifier here, together with the [attr] selector:您可以在此处使用element.querySelectorAll():not修饰符,以及[attr]选择器:

var nonFooElements = parentElement.querySelectorAll("*:not([foo])");

Be aware that this sort of call will be moderately expensive because the selector doesn't begin with an id or a classname, so don't do huge amounts of it.请注意,这种调用的成本会适中,因为选择器不是以 id 或类名开头,所以不要大量调用。

I adapted this answer from this one: https://stackoverflow.com/a/21975970/5009210我从这个答案改编了这个答案: https : //stackoverflow.com/a/21975970/5009210

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用javascript选择元素的所有子元素并更改CSS属性? - How to select all children of an element with javascript and change CSS property? 使用javascript选择DOM的所有元素,但特定元素的所有子元素除外 - Select all element of the DOM with javascript except all the children of a particular element 将鼠标悬停在子元素上时如何 select 所有子元素 - How to select all children elements when hovered over a children element 如何在 JavaScript 的对象数组中将子对象递归分组? - How can i recursively group children objects under parent in an array of objects in JavaScript? 递归得到所有孩子 - Recursively get all children TypeScript或JS-如何选择元素及其所有子元素进入HTMLCollection? - TypeScript or JS- How to select an element and all its children into a HTMLCollection? 如何在 Javascript 中获取元素及其子元素的所有计算 css 属性 - How get all computed css properties of element and its children in Javascript 如何使用 JavaScript 将所有 HTML 元素子元素移动到另一个父元素? - How to move all HTML element children to another parent using JavaScript? 递归地记录dom中所有孩子的所有孩子 - recursively log all children of all children in dom Javascript选择儿童的孩子? - Javascript Select Children of Children?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM