Manipulating classes with jQuery / Javascript

Asked

Viewed 221 times

0

Within the hierarchy below, how can I manipulate a class given to the <th> after clicking on an element within the <td>? Remembering that there are several tables like this.

<table>
  <thead>
   <tr>
    <th class=""></th>
   </tr>
  </thead>
  <tbody>
    <tr>
     <td></td>
    </tr>
  </tdody>
<table>

Thank you!

1 answer

1


Just assign one event to each td, link each with its th through the classes, and when you click on dom until the table to find their th

that climbing in the dom is only necessary if you have more than one table

$(document).ready(function(){
	$('table tbody tr td').each(function(el) {
  	
  	$(this).on('click', function(el) {
    	alert( $(this).closest('table').find( "th."+$(this).attr('class') ).text() );
    })
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
   <tr>
    <th class="item1">th</th>
    <th class="item2">th1</th>
    <th class="item3">th2</th>
    <th class="item4">th3</th>
    <th class="item5">th4</th>
   </tr>
  </thead>
  <tbody>
    <tr>
     <td class="item1">td</td>
     <td class="item2">td1</td>
     <td class="item3">td2</td>
     <td class="item4">td3</td>
     <td class="item5">td4</td>
    </tr>
  </tbody>
<table>

  • 1

    That’s right Felipe! Thanks!

  • Denada! , do not forget to select the answer that helped you as best, stay in the upper left corner, below the votes, this helps the site and other users

Browser other questions tagged

You are not signed in. Login or sign up in order to post.