Reputation: 21
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
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
Reputation: 5175
Try this:
var x = document.getElementById('test').getAttribute('name')
Upvotes: 0
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