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

喜欢的东西:

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

当前回答

你可以使用getAttribute:

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

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

其他回答

你可以使用getAttribute:

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

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

现代浏览器支持本机querySelectorAll,所以你可以:

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

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

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

http://quirksmode.org/dom/core/#t14 http://caniuse.com/queryselector

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

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

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

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

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

你的:

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

使用querySelectorAll():

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

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

关于“CSS”属性选择器的更多信息,请参见https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

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

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