【问题标题】:It's possible to get only the elements inside a specific element using document.querySelectorAll()?是否可以使用 document.querySelectorAll() 仅获取特定元素内的元素?
【发布时间】:2021-08-07 18:08:27
【问题描述】:

所以我有一个看起来像这样的函数:

function myFunc(targetElements, otherThings... ){
let elements = document.querySelectorAll(targetElements);
//...
//otherThings...
}

但有时我需要这个函数来仅访问我在函数外部已经拥有的特定元素内的元素,而不是让函数在整个文档的元素中执行,如下所示:

let ul = document.querySelector('#mySpecificUl');
//should use myFunc(childsOfUl, otherThings... ) to perform in the elements "a" inside "ul"

我想知道是否可以在不必更改我已经拥有的功能的情况下做到这一点,可能看起来像这样:

let ul = document.querySelector('#mySpecificUl');
myFunc(ul > "a", otherThings...); //like this or something

为了更清楚,我想知道是否可以将 document.querySelectorAll() 的范围限制为仅在元素的特定子元素中执行, 可以像这样工作的东西:

ul.querySelectorAll()

但有

document.querySelectorAll()

它可能看起来像 document.querySelectorAll(ul > "a"); 之类的。

感谢所有抽出时间的人。

【问题讨论】:

  • querySelector()querySelectorAll() 方法使用 CSS syntax 来定位 DOM 元素。因此,只要您提供正确的 css 语法,您就可以定位任何您想要的目标。比如document.querySelectorAll('ul > a')...

标签: javascript selectors-api


【解决方案1】:

Elements have 也是querySelectorAll 方法:

let ul = document.querySelector('#mySpecificUl');
ul.querySelectorAll('a') // will contain all <a> descendants of #mySpecificUl

如果您不想先选择元素,可以在单个querySelectorAll 中使用后代选择器(空格)或子选择器(&gt;)进行:

// children
document.querySelectorAll('#mySpecificUl > a')
// all descendants
document.querySelectorAll('#mySpecificUl a')

【讨论】:

  • 感谢您的回答,但我一直在寻找的是使用 document.querySelector 来替代这个 ul.querySelector,我什至在问题的末尾写了它
  • @KleberGermano 如果您的“父”元素,即您想要开始搜索的元素,它本身有一个 id 或一个唯一的类,那么您可以通过一个简单的选择器来完成。您还没有明确说明为什么您不想明确执行此答案中的建议。
  • Tks 很多@CeratinPerformance,第二部分是我要找的
  • @Pointy 答案已被编辑,添加的第二部分正是我正在寻找的内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 2022-10-15
相关资源
最近更新 更多