Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jan 2005
    Posts
    470
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Question A HREF and this.id

    I have found that in both Firefox and Internet Explorer if I try to pass a function the "id" attribute of an href element using "this.id" it will not work for whatever reason.

    For instance, the following will always throw an error:
    Code:
    function getValue(element_id) {
         var element = document.getElementById(element_id);
         var the_inner_html = element.innerHTML;
         alert(the_inner_html);
    }
    
    <a id="the_href_id" href="javascript:getValue(this.id);">Get the value</a>
    The line var the_inner_html = element.innerHTML; throws the error: 'element' has no properties

    However, if I manually assign the id then everything works fine:
    Code:
    <a id="the_href_id" href="javascript:getValue('the_href_id');">Get the value</a>
    Why does the "A HREF" element behave in this way? Are their other document elements that cannot read from this.id?

  • #2
    Senior Coder nikkiH's Avatar
    Join Date
    Jun 2005
    Location
    Near Chicago, IL, USA
    Posts
    1,973
    Thanks
    1
    Thanked 32 Times in 31 Posts
    'this' specifically points to the thing being used right this very moment.
    Which at that moment, is the href property of a link. Not the link itself.

    If you do it this way, it should work fine.

    <a id="the_href_id" href="#" onClick="getValue(this.id);return false;">Get the value</a>

    If this post contains any code, I may or may not have tested it. It's probably just example code, so no getting knickers in a bunch over a typo, OK? If it doesn't have basic error checking in it, such as object detection or checking if objects are null before using them, put that in there. I'm giving examples, not typing up your whole app for you. You run code at your own risk.
    Bored? Visit
    http://www.kaelisspace.com/

  • #3
    Regular Coder
    Join Date
    Jan 2005
    Posts
    470
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Ahh, that explains that!

    Thanks again!


  •  

    Posting Permissions

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