通过属性名称获取HTML元素
There are methods available in JavaScript to get HTML elements using their ID, Class and Tag.
JavaScript中有一些方法可以使用ID,Class和Tag来获取HTML元素。
document.getElementByID(*id*);
document.getElementsByClassName(*class*);
document.getElementsByTagName(*tag*);
Is there any method available to get the elements according to the attribute name.
是否有任何方法可以根据属性名称获取元素。
EX:
EX:
<span property="v:name">Basil Grilled Tomatoes and Onions</span>
Like:
喜欢:
document.getElementsByAttributeName("property");
6 个解决方案
#1
52
Yes, but it isn't present in all browsers. Old versions of Internet Explorer (i.e. before version 8) do not support it. The function is querySelectorAll
(or querySelector
for a single element), which allows you to use CSS selectors to find elements.
是的,但它并不存在于所有浏览器中。旧版本的Internet Explorer(即版本8之前)不支持它。该函数是querySelectorAll(或单个元素的querySelector),它允许您使用CSS选择器来查找元素。
document.querySelectorAll('[property]'); // All with attribute named "property"
document.querySelectorAll('[property=value]'); // All with "property" set to "value" exactly.
(Complete list of attribute selectors on MDN.)
(MDN上的属性选择器的完整列表。)
This finds all elements with the attribute property. It would be better to specify a tag name if possible:
这将查找具有attribute属性的所有元素。如果可能,最好指定标签名称:
document.querySelectorAll('span[property]');
You can work around this if necessary by looping through all the elements on the page to see whether they have the attribute set:
如有必要,您可以通过循环遍历页面上的所有元素来查看它们是否具有属性集:
var withProperty = [],
els = document.getElementsByTagName('span'), // or '*' for all types of element
i = 0;
for (i = 0; i < els.length; i++) {
if (els[i].hasAttribute('property')) {
withProperty.push(els[i]);
}
}
Libraries such as jQuery handle this for you: it's probably a good idea to let them do the heavy lifting.
像jQuery这样的库为你处理这个问题:让他们做繁重的工作可能是一个好主意。
更多相关文章
- Jquery在两个元素之间更改文本
- 扩展htmlhelper.DropDownListFor 支持list数据源和option增加属
- 8.HTML5 CSS3 背景、边框与补丁相关属性
- HTML5<meta name="viewport"/>标签常见属性及说明
- HTML基础 img标签alt属性 当图片加载失败的时候显示为文本
- HTML哪些是块级元素,哪些是行内元素、
- 基于html属性为gulp构建过程添加条件
- 如何使用CSS消除元素的偏移?
- KeyPress或KeyDown事件没有得到html元素的buind