SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Aug 2011
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to retrieve this id value?

    Hi,

    How do I get the id value of the header into the alert in the next example:

    HTML Code:
    <!DOCTYPE html>
    <head>
    <script>
    function showID() {
        //return this; doesn't work
        ID = this.id;
        alert ('ID is: ' + ID);
    }
    </script>
    </head>
    <body>
    <h6 id="header" onclick="showID()">Header</h6>
    </body>
    </html>
    I'm now getting 'undefined' as result. I can put the function inline, as in onclick="alert('ID is: ' + this.id)", but I need it to work the other way.

    Thanx in advance.

  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    When you attach an event handler inline, i.e.: onclick="showID()", within the function this refers to window.

    Use:

    Code:
    onclick="alert( this.id )"
    -or-

    Code:
    onclick="showID( this )"
    
    /* combined with */
    
    function showID( elem) 
    {
      alert ( 'ID is: ' + elem.id );
    }
    or attach the handler properly:

    Code:
    document.getElementById( 'header' ).onclick = showID; /* Ensure element has been rendered at this point.*/
    Tab-indentation is a crime against humanity.

  3. #3
    SitePoint Enthusiast
    Join Date
    Aug 2011
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, Ali! Not only for the solution, but also for explaining which mistake I made.

    The second method you gave is the right one for this job.

    Cheers!

  4. #4
    SitePoint Enthusiast
    Join Date
    Aug 2011
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ali,

    You might be interested in what I needed it for. The answer is: a super simpel and super short javascript with which one can turn a normal multi-level CSS menu in one that also works on touchscreen devices (on which there is no hovering)... Check it out and let me know what you think of it: link.


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
  •