根据属性值在DOM中查找元素 [英] Find an element in DOM based on an attribute value
问题描述
类似于:
doc.findElementByAttribute(myAttribute,aValue);
更新:过去几年,景观发生了巨变。您现在可以可靠地使用 querySelector
和 querySelectorAll
,请参阅 Wojtek的答案如何做到这一点。
现在不需要一个jQuery依赖。如果你正在使用jQuery,那么很好,如果你不这样做,你不需要依靠属性来选择元素。
在vanilla javascript中没有一个很简单的方法,但有一些解决方案可用。
如果像 jQuery 这样的图书馆是一个选择,你可以轻松一点,就像这个:
$([myAttribute = value])
如果该值不是有效的 CSS标识符(它在其中有空格或标点符号等),您需要引用价值(可以是单或双):
$([myAttribute =我的价值'])
您还可以使用 code>,结束与
,包含
等... 属性选择器有几个选项。
Can you please tell me if there is any DOM API which search for an element with given attribute name and attribute value:
Something like:
doc.findElementByAttribute("myAttribute", "aValue");
Update: In the past few years the landscape has changed drastically. You can now reliably use querySelector
and querySelectorAll
, see Wojtek's answer for how to do this.
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.
There's not a very short way to do this in vanilla javascript, but there are some solutions available.
You do something like this, looping through elements and checking the attribute
If a library like jQuery is an option, you can do it a bit easier, like this:
$("[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):
$("[myAttribute='my value']")
You can also do start-with
, ends-with
, contains
, etc...there are several options for the attribute selector.
这篇关于根据属性值在DOM中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!