你能告诉我是否有任何DOM API可以搜索给定属性名和属性值的元素吗?

喜欢的东西:

doc.findElementByAttribute("myAttribute", "aValue");

当前回答

很简单,试试这个

<!DOCTYPE html>
<html>
<body>
<h1>The Document Object</h1>
<h2>The querySelector() Method</h2>

<h3>Add a background color to the first p element:</h3>
<p>This is a p element.</p>
<p data-vid="1">This is a p element.</p>
<p data-vid="2">This is a p element.</p>
<p data-vid="3">This is a p element.</p>

<script>
document.querySelector("p[data-vid='1']").style.backgroundColor = "red";
document.querySelector("p[data-vid='2']").style.backgroundColor = "pink";
document.querySelector("p[data-vid='3']").style.backgroundColor = "blue";
</script>

</body>
</html>

其他回答

下面是一个例子,如何通过src属性在文档中搜索图像:

document.querySelectorAll("img[src='https://pbs.twimg.com/profile_images/........jpg']");

使用查询选择器,示例如下:

document.querySelectorAll(' input[name], [id|=view], [class~=button] ')

input[name]输入带有name属性的元素。

[id|=view] id为view-开头的元素。

[class~=button]包含按钮类的元素。

很简单,试试这个

<!DOCTYPE html>
<html>
<body>
<h1>The Document Object</h1>
<h2>The querySelector() Method</h2>

<h3>Add a background color to the first p element:</h3>
<p>This is a p element.</p>
<p data-vid="1">This is a p element.</p>
<p data-vid="2">This is a p element.</p>
<p data-vid="3">This is a p element.</p>

<script>
document.querySelector("p[data-vid='1']").style.backgroundColor = "red";
document.querySelector("p[data-vid='2']").style.backgroundColor = "pink";
document.querySelector("p[data-vid='3']").style.backgroundColor = "blue";
</script>

</body>
</html>
FindByAttributeValue("Attribute-Name", "Attribute-Value");   

附注:如果你知道确切的元素类型,你可以添加第三个参数(i.e.div, a, p…等等…):

FindByAttributeValue("Attribute-Name", "Attribute-Value", "div");   

但首先,定义这个函数:

function FindByAttributeValue(attribute, value, element_type)    {
  element_type = element_type || "*";
  var All = document.getElementsByTagName(element_type);
  for (var i = 0; i < All.length; i++)       {
    if (All[i].getAttribute(attribute) == value) { return All[i]; }
  }
}

附注:根据评论建议更新。

Daniel De León的回答 它可以用来搜索 ^= - filters id(或任何其他attr)以view关键字开头的元素

document.querySelectorAll("[id^='view']")