简体   繁体   中英

How to create an Object with all attributes of a html tag?

Here is my test code, extracted from a form I'm building:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
function ini(){
    console.log("Element dump:");
    var elem = document.querySelector('form[name="form"] input[name="dataNasc"]');
    for(var i in elem){
        console.log(i+":"+elem[i]);
    }
    console.log("Form element dump:");
    var Form = document.forms["form"];
    var input = Form.dataNasc;
    for(var i in input){
        console.log(i+":"+input[i]);
    }
}
</script>
<title>Untitled Document</title>
</head>

<body onload="ini();">
<form name="form" action="" method="post">
                <label for="dataNasc">Data Nasc.</label>
                <input type="text" name="dataNasc" maxlength="10" required="required" tipo="data" value="{dataNasc}" />
</form>
</body>
</html>

In both cases that I pick the input tag (ini function), the attribute "tipo" is not listed. The property returns "undefined". It seams an object is created using the information in the tag, not a conversion "tag to object". Using outerHTML, I can do it manually (hope this property is cross-browser), but I'm wondering if there is a way using JavaScript resources... How can I do it?

Once you have a reference to the element, you can iterate over its attributes NamedNodeMap to discover all of its attributes. So for example and assuming there will only be one matching element matching your selector...

var elt=document.querySelector('form[name="form"] input[name="dataNasc"]'),
    attrs=elt ? elt.attributes : [];

for(var i=0; i<attrs.length; i++) {
    console.log('attr "'+attrs[i].name+'" contains "'+attrs[i].value+'"');
}

try this:

function ini(){
    console.log("Element dump:");
    var elem = document.querySelector('form[name="form"] input[name="dataNasc"]');
    for(var i in elem){
        console.log(i+":"+elem[i]);
    }
     console.log("Form element dump:");
    var Form = document.forms["form"];
    var input = Form.dataNasc;
     var myObj = {};
     for(var i in input){
         myObj[i] = input[i];
    }
 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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