根据属性值在DOM中查找元素 [英] Find an element in DOM based on an attribute value

查看:455
本文介绍了根据属性值在DOM中查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



类似于:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆