0

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>

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.