在纯 Javascript 中获取元素的属性名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29596551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:46:18  来源:igfitidea点击:

Get attribute name of element in Pure Javascript

javascripthtmldom

提问by Minh Bang

Here is a demo code:

这是一个演示代码:

<div id="demo" myAttribute="ok"></div>

Here are 2 things I want
1) the attribute name, ie: 'myAttribute'.
2) the element that contains the attribute 'myAttribute', ie: the div.

这是我想要的两件事
1) 属性名称,即:'myAttribute'。
2) 包含属性“myAttribute”的元素,即:div。

回答by Paul S.

To get a NodeListof Nodesthat match a selector

获取与选择器匹配的节点NodeList

var list = document.querySelectorAll('[myAttribute]');

listwill be Array-likebut not inherit from Array. You can loop over it with forand list.length

list将是Array-like但不是从Array继承。您可以使用for和循环遍历它list.length



To get a NamedNodeMapof the attributeson an Element

要获得的NamedNodeMap中的属性上的元素

var nnm = elem.attributes;

nnmwill be Array-likebut not inherit from Array. You can loop over it with forand nnm.length

nnm将是Array-like但不是从Array继承。您可以使用for和循环遍历它nnm.length



To get the valueof an attributeon an Elementuse .getAttribute

要获取元素上的属性,请使用.getAttribute

var val = elem.getAttribute('myAttribute');

valwill be nullif there is no such attribute

valnull如果没有这样的属性,将会是



To test the existance of an attributeon an Elementuse .hasAttribute

要测试元素上的属性是否存在,请使用.hasAttribute

var b = elem.hasAttribute('myAttribute');

bwill be a Booleanvalue, trueor false

b将是一个布尔值,truefalse

回答by whoacowboy

Using jQuery you could do something like this.

使用 jQuery 你可以做这样的事情。

div = $("[myAttribute]");
attrValue = div.attr('myAttribute');

divwould be the jQuery element.
attrValuewould be 'ok'

div将是 jQuery 元素。
attrValue会“好的”