2

I have been having a lot of trouble trying to get value into javascript and pass it to alert. Here is the code that I use to pass the value....

        <img onclick="handpost()" id="colorface" name="red" src="http://www.asl-ela.org/image/redface.png" alt="Red face" /></a>

Then I use function to get the data from img tag....

<script type="text/javascript">
   function handpost()  {
      var color = document.getElementById('colorface').name;
      alert(color);
   }
</script>

I keep getting alert box saying undefined. What does that mean?!?!?!

3
  • name is not an <img> property Commented May 29, 2016 at 1:51
  • 1
    Since name is a property of img element. You should use getAttribute to get its value, try this document.getElementById('colorface').getAttribute('name') Commented May 29, 2016 at 1:51
  • Since name is not a standard property on img attributes, you shouldn't use it. Instead, it is better to use data-name as the whole data-* realm as been reserved for custom values. developer.mozilla.org/en-US/docs/Web/Guide/HTML/… .. these values can also be accessed via jQuery's data method or getAttribute('data-name') Commented May 29, 2016 at 1:57

3 Answers 3

9

It means exactly what it reads: document.getElementById('colorface').name is undefined. document.getElementById('colorface') may exist but it doesn't have property name. Try document.getElementById('colorface').getAttribute('name').
name is not standard attribute of img but if you add it then you can access it. enter image description here

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

2 Comments

I changed name to .getAttribute('name') and it works.
Hi Alex, I did use the code that you suggested. I tried it and the alert box says null. I tried it in jfiddle and it works as it says red. So what is going on? Thanks
3

Use the following instead :

var color = document.getElementById('colorface').getAttribute('name');

Comments

0

Not sure how could you get it as undefined

Element.name, name gets or sets the name property of a DOM object; it only applies to the following elements: <a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, <input>, <map>, <meta>, <object>, <param>, <select>, and <textarea>(From MDN)

function handpost() {
  var color = document.getElementById('colorface').name;
  alert(color);
}
<img onclick="handpost()" id="colorface" name="red" src="http://www.asl-ela.org/image/redface.png" alt="Red face" />

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.