Search code examples
javascriptparent

javascript parent of parent


In javascript is there an easy way to target the parent of a parent?

I'm using this.parentNode as the element of a function to select the parent, and I tried both this.parent.parentNode and this.parentNode.parentNode, but both simply return the direct parent.
I'm trying to affect the div surrounding the div surrounding the 'this'. I did manage to make it work using a simple loop statement that repeats the parentNode selection twice, but I assume there's a better way.


Solution

  • this.parentNode.parentNode is correct, you must (with apologies!) have had a mistake in the test where you tried it.

    Example: Live Copy | Source

    HTML:

    <div id="outermost">Outermost
      <div id="inner1">Inner 1
        <div id="inner2">Inner 2</div>
      </div>
    </div>
    

    JavaScript:

    var inner2 = document.getElementById("inner2");
    
    display("inner2.id = " + inner2.id);
    display("inner2.parentNode.id = " + inner2.parentNode.id);
    display("inner2.parentNode.parentNode.id = " + inner2.parentNode.parentNode.id);
    
    display("Try clicking the blue 'inner2' above");
    
    inner2.onclick = function(e) {
      display("Click: this.id = " + this.id);
      if (this.parentNode) {
        display("Click: this.parentNode.id = " + this.parentNode.id);
        if (this.parentNode.parentNode) {
          display("Click: this.parentNode.parentNode.id = " + this.parentNode.parentNode.id);
        }
      }
    };
    
    function display(msg) {
      var p = document.createElement('p');
      p.innerHTML = String(msg);
      document.body.appendChild(p);
    }
    

    Output (assuming one clicks as directed):

    inner2.id = inner2
    inner2.parentNode.id = inner1
    inner2.parentNode.parentNode.id = outermost
    Try clicking the blue 'inner2' above
    Click: e.target.id = inner2
    Click: e.target.parentNode.id = inner1
    Click: e.target.parentNode.parentNode.id = outermost