简体   繁体   English

使用javascript获取html元素的所有属性

[英]get all attributes of an html element using javascript

How can I get all attributes of an HTML element?如何获取 HTML 元素的所有属性? For example I have an element:例如我有一个元素:

<input type="text" class"cls1" id="myId" name="myName"/> 

and I want to see all attributes/properties that can be used for this input and not only attribute assigned already (type, class, id, name) on but all available attributes that can be used on this element.并且我想查看可用于此输入的所有属性/属性,不仅是已分配的属性(类型、类、ID、名称),而且是可用于此元素的所有可用属性。

With this method I can see only assigned attributes :|使用这种方法,我只能看到分配的属性:|

var attr = document.getElementById("myId").attributes;
console.log(attr);
var el = document.getElementById("myId");

var nodes=[], values=[];
for (var att, i = 0, atts = el.attributes, n = atts.length; i < n; i++){
    att = atts[i];
    nodes.push(att.nodeName);
    values.push(att.nodeValue);
    console.log(att.nodeName + " - " + att.nodeValue);
}

试试console.dir()

console.dir(document.getElementById('myId'));

You can do this,你可以这样做,

 var attr = document.getElementById("myId").attributes; for (var key in attr) { if (typeof attr[key] != 'function') console.log(attr[key]); }

var attr = document.getElementById("myId").attributes; for (var key in attr) { var element = attr[key]; if (typeof element === "object") { console.log(element.name); console.log(element.value); } }

I think you can get all the enumerable properties using我认为您可以使用

var el = document.getElementById("myId");
var props = Object.keys(el); //will return an array of properties

Demo: Fiddle演示:小提琴

Object.Keys() - For older browsers use a polyfill Object.Keys() -对于旧的浏览器使用填充工具

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM