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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2694640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:28:56  来源:igfitidea点击:

Find an element in DOM based on an attribute value

javascriptdom

提问by michael

Can you please tell me if there is any DOM API which search for an element with given attribute name and attribute value:

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

Something like:

就像是:

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

采纳答案by Nick Craver

Update:In the past few years the landscape has changed drastically. You can now reliably use querySelectorand querySelectorAll, see Wojtek's answerfor how to do this.

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

There's no need for a jQuery dependency now. If you're using jQuery, great...if you're not, you need not rely it on just for selecting elements by attributes anymore.

现在不需要 jQuery 依赖项。如果您正在使用 jQuery,那太好​​了……如果不是,您就不必再依赖它来仅按属性选择元素了。



There's not a very short way to do this in vanilla javascript, but there are some solutions available.

在 vanilla javascript 中没有很短的方法可以做到这一点,但有一些可用的解决方案。

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

你做这样的事情,循环遍历元素并检查属性

If a library like jQueryis an option, you can do it a bit easier, like this:

如果像jQuery这样的库是一个选项,您可以更轻松地完成它,如下所示:

$("[myAttribute=value]")

If the value isn't a valid CSS identifier(it has spaces or punctuation in it, etc.), you need quotes around the value (they can be single or double):

如果该值不是有效的CSS 标识符(其中包含空格或标点符号等),则需要在该值周围加上引号(它们可以是单引号或双引号):

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

You can also do start-with, ends-with, contains, etc...there are several options for the attribute selector.

您还可以执行start-withends-withcontains等...属性选择器有多个选项

回答by Wojtek Kruszewski

Modern browsers support native querySelectorAllso you can do:

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

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

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

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

Details about browser compatibility:

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

You can use jQuery to support obsolete browsers (IE9 and older):

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

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

回答by Naveen Pantra

We can use attribute selector in DOM by using document.querySelector()and document.querySelectorAll()methods.

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

for yours:

给你的:

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

and by using querySlectorAll():

并通过使用querySlectorAll()

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

In querySelector()and querySelectorAll()methods we can select objects as we select in "CSS".

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

More about "CSS" attribute selectors in https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

更多关于https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors 中的“CSS”属性选择器

回答by T.Todua

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

p.s. if you know exact element-type, you add 3rd parameter (i.e.div, a, p ...etc...):

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

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

but at first, define this function:

但首先,定义这个函数:

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. updated per comments recommendations.

ps 根据评论建议更新。

回答by KhaledDev

Here is an example , How to search images in a document by src attribute :

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

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

回答by Deke

you could use getAttribute:

你可以使用 getAttribute:

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

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

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