通过属性名称获取HTML元素 [英] Getting HTML elements by their attribute names

查看:91
本文介绍了通过属性名称获取HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  document.getElementByID(*)可以使用JavaScript中的方法来获取HTML元素, ID*); 
document.getElementsByClassName(* class *);
document.getElementsByTagName(* tag *);

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



EX:

 < span property =v:name>和洋葱< / span> 

喜欢:

 code> document.getElementsByAttributeName( 属性); 


解决方案

是的,但不存在于所有浏览器。旧版本的Internet Explorer(即版本8之前)不支持它。对于单个元素,该函数是 querySelectorAll (或 querySelector ),它允许您使用CSS选择器来查找元素。

  document.querySelectorAll('[property]'); //所有属性名为property
document.querySelectorAll('[property = value]'); //所有的属性设置为值。

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



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

  document.querySelectorAll('span [property]'); 

如果需要,您可以通过循环访问页面上的所有元素来查看是否有属性集:

  var withProperty = [],
els = document.getElementsByTagName('span')/ /或'*'用于所有类型的元素
i = 0; (i = 0; i< els.length; i ++){
if(els [i] .hasAttribute('property')){
withProperty.push (ELS [I]);
}
}

像jQuery这样的库会为你处理这个:可能一个很好的主意让他们做得很重。


There are methods available in JavaScript to get HTML elements using their ID, Class and Tag.

document.getElementByID(*id*);
document.getElementsByClassName(*class*);
document.getElementsByTagName(*tag*);

Is there any method available to get the elements according to the attribute name.

EX:

<span property="v:name">Basil Grilled Tomatoes and Onions</span>

Like:

document.getElementsByAttributeName("property");

解决方案

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.

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.)

This finds all elements with the attribute property. It would be better to specify a tag name if possible:

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.

这篇关于通过属性名称获取HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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