8

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

12

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">
Sign up to request clarification or add additional context in comments.

1 Comment

Also, in most browsers you can access data--attributes directly via dataset property. E.g. document.getElementById('buy').dataset.token.
2

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/

2 Comments

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.
adding to that. Perhaps single word attributes will be a problem as they might find their way in the standard (token is not a good choice). I´d stick with multi word attributes like the official data- but feel fine using a custom- prefix just to be sure and future sane.

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.