axel
axel

Reputation: 21

Get an attribute name with document.getelementbyid in js

Why is it doesn't work?

var x = document.getElementById('test').name;
alert(x); // jhon
<div id='test' name='jhon'> its just a text </div>

Upvotes: 0

Views: 1871

Answers (3)

Quentin
Quentin

Reputation: 943220

Div elements are not allowed name attributes, so there is no matching property for them on the DOM.

If you want to store custom data on an element, use a data-* attribute.

If you really want to use invalid HTML you can access it with the getAttribute method.

Upvotes: 6

IsraGab
IsraGab

Reputation: 5175

Try this:

 var x = document.getElementById('test').getAttribute('name')

Upvotes: 0

VIshal Jain
VIshal Jain

Reputation: 622

You will have to use getAttribute method to get value of any attribute of html element

   var x = document.getElementById('test').getAttribute("name");
   console.log(x)
<div id='test' name='jhon'> its just a text </div>

Upvotes: 0

Related Questions