SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2005
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Read custom attributes

    Let's say i defined my own attribute, called "counter".
    Code HTML4Strict:
    <div id="myid" counter="2">test</div>

    I know I can read this value trough:
    document.getElementById('myid').getAttribute('counter');

    But is it possible to add the counter attribute to javascripts known attributes, so I could access it like:
    document.getElementById('myid').counter;

    ?

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,875
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    I don't think you can access any of the attributes of an X(HT)ML document that way from JavaScript - you need to identify the namespace that the attribute you are defining is to be in.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    99
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Put this in separate js file and include it on page where you want to use it
    Code JavaScript:
    Object.prototype; {
    	counter: function(){return this.getAttribute('counter')}
    }

    Then you can use
    Code JavaScript:
    document.getElementById('myid').counter;
    to get value of counter attribute

  4. #4
    SitePoint Enthusiast
    Join Date
    Nov 2005
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    @bosko:

    That dosen't seem to work. Just returns undefined. The following works, but is not what I'm looking for:

    Code JavaScript:
    Object.prototype.counter = function(){ 
    	return this.getAttribute('counter');
    }

    And then
    Code JavaScript:
    document.getElementById('mydiv').counter();


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •