通过属性名称获取HTML元素

Sau*_*ena 50 html javascript dom

JavaScript中有一些方法可以使用ID,Class和Tag来获取HTML元素.

document.getElementByID(*id*);
document.getElementsByClassName(*class*);
document.getElementsByTagName(*tag*);
Run Code Online (Sandbox Code Playgroud)

是否有任何方法可以根据属性名称获取元素.

EX:

<span property="v:name">Basil Grilled Tomatoes and Onions</span>
Run Code Online (Sandbox Code Playgroud)

喜欢:

document.getElementsByAttributeName("property");
Run Code Online (Sandbox Code Playgroud)

lon*_*day 75

是的,但它并不存在于所有浏览器中.旧版本的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.
Run Code Online (Sandbox Code Playgroud)

(MDN上的属性选择器的完整列表.)

这将查找具有attribute属性的所有元素.如果可能,最好指定标签名称:

document.querySelectorAll('span[property]');
Run Code Online (Sandbox Code Playgroud)

如有必要,您可以通过循环遍历页面上的所有元素来查看它们是否具有属性集:

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]);
    }
}
Run Code Online (Sandbox Code Playgroud)

像jQuery这样的库可以为你处理这个问题:让他们做繁重的工作可能是个好主意.


Moh*_*alo 7

假设您有一个输入:

         <input type='text' name='from'/>
  
Run Code Online (Sandbox Code Playgroud)

然后您可以按如下方式访问它:

        document.querySelector('input[name="from"]')
Run Code Online (Sandbox Code Playgroud)