如何使用选择器获取相对于element实例的元素

How do you grab an element relative to an Element instance with a selector?

本文关键字:实例 元素 element 相对于 何使用 选择器 获取      更新时间:2023-09-26

我正在编写一个小库,需要通过querySelector方法选择目标元素的相对元素。

例如:

HTML

<div class="target"></div>
<div class="relative"></div>
<!-- querySelector will select only this .target element -->
<div class="target"></div>
<div class="relative"></div>
<div class="target"></div>
<div class="relative"></div>

JavaScript

var target = document.querySelectorAll('.target')[1];
// Something like this which doesn't work actually
var relativeElement = target.querySelector('this + .relative');

在上面的示例中,我试图仅相对于值存储在target变量中的.target元素来选择.relative类元素。任何样式都不应应用于其他.relative类元素。

PS:选择器可能会有所不同。因此,我不能使用JavaScript的预定义方法,如previousElementSiblingnextElementSibling

我不需要jQuery或其他JavaScript库中的解决方案。

理想情况下应该是:

var relativeElement = target.querySelector('.relative');

但这实际上会尝试在目标元素中选择一些内容。因此,只有当您的html结构类似于时,这才会起作用

<div class="target">
 <div class="relative"></div>
</div>

在这种情况下,你最好的选择可能是使用nextElementSibling,我知道你很难使用它。

您不能如果你坚持使用主题元素的querySelector,答案是没有办法。

规范和MDN都明确表示Element.querySelector必须返回"调用它的元素的子代",而您想要的对象元素不满足此限制。

如果你想爆发,你必须上去使用其他元素,例如document.querySelector

您可以随时覆盖Element.prototype.querySelector来进行竞价,包括实现自己的CSS引擎,以任何语法选择您想要的任何元素。我没有提到这一点,因为你将打破对一个非常重要的函数的假设,很容易破坏其他库甚至普通代码,或者充其量会减慢它们的速度。

target.querySelector('.relative');

通过在目标而不是文档上使用querySelector,可以将DOM遍历范围扩大到目标元素。从你的解释中还不完全清楚,但我认为你所说的亲属是指后代?

要获得所有目标元素,可以使用

document.querySelectorAll('.target')

然后迭代结果

我找到了一种适用于我的库的方法。

我将用一个唯一的自定义属性值替换querySelector中的"this "。类似这样的东西:

Element.prototype.customQuerySelector = function(selector){
    // Adding a custom attribute to refer for selector
    this.setAttribute('data-unique-id', '1');
    // Replace "this " string with custom attribute's value
    // You can also add a unique class name instead of adding custom attribute
    selector = selector.replace("this ", '[data-unique-id="1"] ');
    // Get the relative element
    var relativeElement = document.querySelector(selector);
    // After getting the relative element, the added custom attribute is useless
    // So, remove it
    this.removeAttribute('data-unique-id');
    // return the fetched element
    return relativeElement;
}
var element = document.querySelectorAll('.target')[1];
var targetElement = element.customQuerySelector('this + .relative');
// Now, do anything with the fetched relative element
targetElement.style.color = "red";

工作Fiddle