简体   繁体   中英

How to get the Exact Parent Item With Class Name In JavaScript?

<div class="wrapped">

  <table id="tabled">
    <tr>
        <td>abc</td>
        <td>def</td>
        <td><input type="checkbox" class="chkbox" id="val" onclick="myFunction(this.id)"></input></td>
    </tr>
    <tr>
        <td>abc</td>
        <td>def</td>
        <td><input type="checkbox" class="chkbox" id="val1" onclick="myFunction(this.id)"></input></td>
    </tr>

  </table>

</div>

The IDs of checkbox are automatically generating with my some code. Plus there is a loop on the DIV with Class Name "wrapped". This whole Code prints for least 2 times. And seems like that

<div class="wrapped">
  <table id="tabled">
    <tr>
        <td>abc</td>
        <td>def</td>
        <td><input type="checkbox" class="chkbox" id="val1" onclick="myFunction(this.id)"></input></td>
    </tr>
  </table>
</div>    

<div class="wrapped">
  <table id="tabled">
    <tr>
        <td>abc</td>
        <td>def</td>
        <td><input type="checkbox" class="chkbox" id="val2" onclick="myFunction(this.id)"></input></td>
    </tr>
  </table>
</div>

Now I am trying to add some JS which help me to get the div with class 'Wrapped'. Here is my js

function myFunction(el) {
    var el = document.getElementById(el);
    var r1 = el.closest(".wrapped");
    alert (r1.innerHTML);
}

It always returns me the HTML of the First div with class 'Wrapped'. What I want is that if i click checkbox with ID val2 it should return me the second div with class 'Wrapped'. But in all my struggle around the net I am only getting first in all options. Thanks In advance

But it is correct and returns desired .wrapped div.

Also you can pass the .wrapped directly to your function:

 onclick="myFunction(this.closest('.wrapped'))"

And js:

function myFunction(wr) {
     alert (wr.innerHTML);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM