如何在没有jquery的情况下通过属性选择项目

How to select an item by attribute without jquery?

本文关键字:属性 选择 项目 情况下 jquery      更新时间:2023-09-26

我需要选择这样的元素:$('[data-key=' + objectId + ']'),但我需要选择这个没有jquery,使用document.querySelector或纯JS上的其他东西。

您可以使用document.querySelectorAll('[data-key=' + objectId + ']')并遍历所有结果

var allKeys = document.querySelectorAll('[data-key=' + objectId + ']');
[].forEach.call(allKeys, function(elem){
   console.log(elem); //Do your stuff with each element
});

你可以试试这个

<p data-test="testquery">
document.querySelectorAll('[data-test]')