Carlos27 Carlos27 - 2 months ago 7
jQuery Question

adding attribute using .index and .attr to th with no class or id

I have the following table

<table class="results">
<thead>
<tr>
<th>Title1</th>
<th>Title2</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>e</td>
</tr>
<tr>
<td>b</td>
<td>f</td>
</tr>
<tr>
<td>c</td>
<td>g</td>
</tr>
<tr>
<td>d</td>
<td>h</td>
</tr>
</tbody>




I'm trying to add different attributes to each
<th>
.. Ideally using jquery .index and .attr

Just not sure how to select the
<th>
when there's no id or class..

I'm guessing that we can use the .results class?

Answer

I want to add different attributes to the 2 th e.g. th class="one" th class="two"

To achieve that you could use an array of the class names which map to the indexes of the th elements in the table. Try this:

var classes = ['one', 'two'];
$('.results th').addClass(function(i) {
  return classes[i];
});
.one {
  color: red;
}
.two {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="results">
  <thead>
    <tr>
      <th>Title1</th>
      <th>Title2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>a</td>
      <td>e</td>
    </tr>
    <tr>
      <td>b</td>
      <td>f</td>
    </tr>
    <tr>
      <td>c</td>
      <td>g</td>
    </tr>
    <tr>
      <td>d</td>
      <td>h</td>
    </tr>
  </tbody>
</table>

Comments