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这样的库为你处理这个问题:让他们做繁重的工作可能是一个好主意。

更多相关文章

  1. Jquery在两个元素之间更改文本
  2. 扩展htmlhelper.DropDownListFor 支持list数据源和option增加属
  3. 8.HTML5 CSS3 背景、边框与补丁相关属性
  4. HTML5<meta name="viewport"/>标签常见属性及说明
  5. HTML基础 img标签alt属性 当图片加载失败的时候显示为文本
  6. HTML哪些是块级元素,哪些是行内元素、
  7. 基于html属性为gulp构建过程添加条件
  8. 如何使用CSS消除元素的偏移?
  9. KeyPress或KeyDown事件没有得到html元素的buind

随机推荐

  1. Mysql PARTITION 数据表分区技术
  2. mysql批量结束线程
  3. MySQL数据库表名、列名、别名区分大小写
  4. 在Google Cloud Platform上设计PolyGlot
  5. mysql存储过程调试记实
  6. Android应用程序与外部数据库之间的安全
  7. [转]MYSQL高可用方案探究(总结)
  8. mysql 的一点点记录
  9. 对于有3亿多万条记录的MySQL表,有哪些优化
  10. centos7 移动mysql5.7.19 数据存储位置