6

Hi im facing problem in this html document please help me

Im very new to this.

May be i am fool to missing something out.

I have put only useful source here to solve please.

<!DOCTYPE html>
<html>
  <body id="owner_profile">
    <a id="buy" owner="789" token="1000" wrapper="purchase" name="oname">Hurray!</a><br>
    <script>
      document.write("You Have: ");
      document.write(document.getElementById('buy').token);
    </script>  
  </body>
</html>

I want it to display token but its giving undefined

Result is :

Hurray!

You Have: undefined

2 Answers 2

11

There is a difference between attributes and properties. To get the attribute, use getAttribute("token").

Many (predefined) attributes are mapped to properties (or the other way around, I don't know). So for example if you set a cell's colSpan property, you will also affect its colspan attribute.

However sometimes the two are very different. Most notably, the value attribute of an input will NOT change if you type in the box. However the value property will. This means that you can always reset a textbox with elem.value = elem.getAttribute("value").

As a general rule, you should always use get/setAttribute to change an elements attributes, because you can't rely on the property being there.

Side-note: Those "attributes" should be data:

<a id="buy" data-owner="789" data-token="1000" data-wrapper="purchase" name="oname">
1
  • 2
    Also, in most browsers you can access data--attributes directly via dataset property. E.g. document.getElementById('buy').dataset.token.
    – katspaugh
    Commented Sep 25, 2012 at 12:04
1

You'll need to use .getAttribute('token') instead of .token, since "token" isn't a valid HTML attribute.

<script>
document.write("You Have: ");
document.write(document.getElementById('buy').getAttribute("token"));
</script>

Working JSFiddle: http://jsfiddle.net/AvKbn/

1
  • 1
    I'd word "not valid" as "custom" instead, yeah browsers don't know what to do with it and it doesn't pass W3C validator, but it's not like it breaks anything. Anyway, I'd recommend using a data- attribute for validness. Commented Sep 8, 2012 at 5:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.