【发布时间】: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')...