简体   繁体   中英

How to select the closest element by first part of classname?

i've this part of a table

<tr class="getmoreinfo_19">
    <td>&nbsp;</td>
    <td colspan="3">
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
             <i class="far fa-window-close getmoreinfo_x"></i>txt
        </div>
    </td>
</tr>

Now i want to hide this on click at the "<i class="far fa-window-close getmoreinfo_x"></i>" icon.

For that i want to toggle a display:none class.

My problem is, that i dont know how i can select the closest "tr" wich has the classname who begins with "getmoreinfo_"?

Is it possible and if its how?

Thanks a lot.

if you're using javascript, then try .closest('tr[class^="getmoreinfo_"]') ,

Please note this is assuming the clicked target is <i> and the tr element always has only class getmoreinfo_ at the beginning . In case your tr has more classes, consider using this:

.closest('tr[class*="getmoreinfo_"]')

<table>
  <tr class="getmoreinfo_1" data-row="1">
    <td>
      <div class="item"><span></span><i class="icon-x">X</i></div>
    </td>
  </tr>
  <tr class="getmoreinfo_1" data-row="2">
    <td>
      <div class="item"><span></span><i class="icon-x">X</i></div>
    </td>
  </tr>
  <tr class="getmoreinfo_1" data-row="3">
    <td>
      <div class="item"><span></span><i class="icon-x">X</i></div>
    </td>
  </tr>
</table>
(function(){
  const icons = document.querySelectorAll('.icon-x');

  function clickHandler(event) {
    const row = event.currentTarget.closest('tr[class*="getmoreinfo_"]');
    console.log(`clicked: ${row.getAttribute('data-row')}`)
  }

  for(const icon of icons) {
    icon.addEventListener('click', clickHandler);
  }
})();

Hope this help

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