document.querySelector在一个元素中包含多个数据属性 [英] document.querySelector multiple data-attributes in one element
问题描述
我正在尝试使用document.querySelector找到一个具有多个数据属性的元素:
I'm trying to find an element with document.querySelector which has multiple data-attributes:
<div class="text-right" data-point-id="7febe088-4eca-493b-8455-385b39ad30e3" data-period="current">-</div>
我想过这样的事情:
document.querySelector('[data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"] [data-period="current"]')
但它不起作用。但是,如果我把第二个数据属性放在像
but it does not work. However, it works well, if I put the second data-attribute in a child-element like
<div class="text-right" data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"> <span data-period="current">-</span> </div>
那么,是否可以同时搜索这两个属性?我已经尝试了几个选项,但我没有得到它。
So, is there an option to search for both attributes at once? I've tried several options but I don't get it.
推荐答案
2个选择器之间不应该有空格
There should not be a space between the 2 selectors
document.querySelector('[data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"][data-period="current"]')
如果你在它们之间留一个空格它将成为后代选择器,即它将搜索元素属性 data-period =当前
这是一个元素,其中 data-point-id =7febe088-4eca-493b-8455-385b39ad30e3
喜欢
if you give a space between them it will become a descendant selector, ie it will search for an element attribute data-period="current"
which is inside an element with data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"
like
<div class="text-right" data-point-id="7febe088-4eca-493b-8455-385b39ad30e3">
<div data-period="current">-</div>
</div>
这篇关于document.querySelector在一个元素中包含多个数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!