如何获取JavaScript中元素的属性值? [英] How can I get the attribute value of an element in JavaScript?

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

问题描述

这是演示代码:

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

这是我想要的两件事

1)属性名称,即: 'myAttribute'。

2)包含属性'myAttribute'的元素,即:div。

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

推荐答案

获取 NodeList 节点中的a>

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

list 将是 Array-类似于,但不能继承自 Array 。您可以使用 for list.length

list will be Array-like but not inherit from Array. You can loop over it with for and list.length

要获取 元素上的属性的NamedNodeMap

To get a NamedNodeMap of the attributes on an Element

var nnm = elem.attributes;

nnm 将是 Array-类似于,但不能继承自 Array 。您可以使用 for nnm.length

nnm will be Array-like but not inherit from Array. You can loop over it with for and nnm.length

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

To get the value of an attribute on an Element use .getAttribute

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

val 将为 null 如果没有这样的 attribute

val will be null if there is no such attribute

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

To test the existance of an attribute on an Element use .hasAttribute

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

b 将是 Boolean 值, true false

这篇关于如何获取JavaScript中元素的属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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