简体   繁体   中英

How do I retrieve an attribute's name using the nodeName property?

You can easily retrieve the tag name of an element using the nodeName , like this:

 var atnode = document.getElementById("link-test"); alert(atnode.nodeName);
 <a href="#" id="link-test">link</a>

But how do I use the nodeName to get the attribute of the element instead?

Using the getAttribute() does not do what I want, because you have to insert the name of the attribute first, and then it just gives you back the value of the attribute. I want to get the name of the attribute just like I did with nodeName . I know nodeName can be used with attribute nodes too, but how?

 const atnode = document.getElementById("link-test"); const nodes=[]; const values=[]; for (let att, i = 0, atts = atnode.attributes, n = atts.length; i < n; i++){ att = atts[i]; nodes.push(att.nodeName); values.push(att.nodeValue); console.log(att.nodeName + " - " + att.nodeValue); }
 <a href="#" id="link-test">link</a>

After using attributes method you can use nodeName to get the attribute name and nodeValue to get the value of the attribute. After pushing it to array you can get attribute and value of it using same index in both arrays.

You can get a list of the attributes with getAttributeNames() on the node. In your example, you could do like so:

atnode.getAttributeNames() This will return ["href", "id"] .

Then you can loop through the list with getAttribute(<item from list as string>) to get the values of the element's attributes.

If I understood right, you just need to use the getAttributeNames method.

Follows an example:

 const exampleElement = document.getElementsByTagName("example")[0]; console.log(exampleElement.getAttributeNames());
 <example name="one" last="two"></example>

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