SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict whydna's Avatar
    Join Date
    Jun 2006
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Javascript referencing the current DOM element?

    Is it possible for javascript to get a reference to the current DOM element it is nested in? For example:

    <a href="#" onClick="function(selfElement);">

    Which would pass into the "function()" a reference to the <a href> element?

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    you would pass the this keyword

    Code javascript:
    <a href="#" onClick="doSomething(this);">

    Code javascript:
    function doSomething(el) {
        // do something with el
    }

    It's not a good idea though to have a link without a useful destination. Nor is it a good idea to have javascript mixed in with the html code.
    Because of this, you should separately attach the onclick event from javascript, which has the nice side-benefit of the this keyword automatically referring to the element that fired the event.

    Code html4strict:
    <a id="myLink" href="somePage.html">

    Code javascript:
    document.getElementById('myLink').onclick = doSomething;
    function doSomething() {
        var el = this; // the element that fired the event
    }

    Another benefit is that the information about the event is also available to you as well.

    Code html4strict:
    <a id="myLink" href="somePage.html">

    Code javascript:
    document.getElementById('myLink').onclick = doSomething;
    function doSomething(evt) {
        evt = evt || window.event; // The event that was fired
        var targ = evt.target || evt.srcElement; // the element that was clicked
        var el = this; // the element that fired the event
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


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
  •