skip to Main Content

I try get id parent p div (class mainRow), but my code in console return undefinied:

<div class="row mainRow" id="someId">
  <div class="selected">
    <p onclick="checkParentId(this)">Hello</p>
  </div>
</div>

<script>

function checkParentId(element){
  var a = $(element).parent( ".mainRow");
  var b  = $(a).attr("id");
  console.log(b);
}
</script>

Link to jsfiddle: https://jsfiddle.net/50ev1jzq/

3

Answers


  1. Chosen as BEST ANSWER

    I find sollution, i change .parent to .closest and code work

    <div class="row mainRow" id="someId">
      <div class="selected">
        <p onclick="checkParentId(this)">Hello</p>
      </div>
    </div>
    
    <script>
    
    function checkParentId(element){
      var a = $(element).closest( ".mainRow");
      var b  = $(a).attr("id");
      console.log(b);
    }
    </script>
    
    

  2. Since the .mainRow is not a parent of the paragraph, use .closest:

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>parent demo</title>
      <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
    </head>
    <body>
     
    <div class="row mainRow" id="someId">
    
    <div class="selected">
    <p onclick="checkParentId(this)">Hello</p>
    </div>
    </div>
     
    <script>
    
    function checkParentId(element){
    debugger
    var a = $(element).closest( ".mainRow" );
    var b  = $(a).attr("id");
    console.log(b);
    }
    
    </script>
     
    </body>
    </html>
    Login or Signup to reply.
  3. You could use parents(), because according to the docs:

    Given a jQuery object that represents a set of DOM elements, the parent() method traverses to the immediate parent of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements.
    This method is similar to .parents(), except .parent() only travels a single level up the DOM tree.

    As others have pointed out, closest() could also work. There are some differences tough:
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search