根据属性值在DOM中查找元素

时间:2010-04-22 21:27:28

标签: javascript dom

是否可以告诉我是否有任何DOM API搜索具有给定属性名称和属性值的元素:

类似的东西:

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

7 个答案:

答案 0 :(得分:322)

现代浏览器支持原生querySelectorAll,因此您可以执行以下操作:

document.querySelectorAll('[data-foo="value"]');

https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

有关浏览器兼容性的详细信息:

您可以使用jQuery来支持过时的浏览器(IE9及更早版本):

$('[data-foo="value"]');

答案 1 :(得分:124)

更新:在过去几年中,景观发生了巨大变化。您现在可以可靠地使用querySelectorquerySelectorAll,请参阅Wojtek's answer了解如何执行此操作。

现在不需要jQuery依赖。如果您正在使用jQuery,那么很好......如果您不是,那么您不必再依赖于按属性选择元素了。


在vanilla javascript中执行此操作的方法不是很短,但有一些解决方案可用。

You do something like this, looping through elements and checking the attribute

如果像jQuery这样的库是一个选项,你可以更容易地做到这一点:

$("[myAttribute=value]")

如果该值不是有效CSS identifier(其中有空格或标点符号等),则需要围绕该值的引号(它们可以是单引号或双引号):

$("[myAttribute='my value']")

您还可以执行start-withends-withcontains等... there are several options for the attribute selector

答案 2 :(得分:20)

我们可以使用document.querySelector()document.querySelectorAll()方法在DOM中使用属性选择器。

为你的:

document.querySelector("selector[myAttribute='aValue']");

并使用querySlectorAll()

document.querySelectorAll("selector[myAttribute='aValue']");

querySelector()querySelectorAll()方法中,我们可以在“CSS”中选择对象。

有关https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

中“CSS”属性选择器的更多信息

答案 3 :(得分:18)

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

P.S。如果您知道确切的元素类型,则添加第三个参数(即div, a, p ...etc...):

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]; }
  }
}

P.S。按评论建议更新。

答案 4 :(得分:4)

你可以使用getAttribute:

 var p = document.getElementById("p");
 var alignP = p.getAttribute("align");

https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

答案 5 :(得分:3)

以下是一个示例,如何通过src属性搜索文档中的图像:

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

答案 6 :(得分:3)

使用查询选择器,例如:

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

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

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

[class~=button]类为button的元素。