kalles kalles - 7 months ago 10
Javascript Question

setting opacity to all <td> except a child in the last <td>

<tbody id="items">
<tr><td>Item 1</td></tr>
<tr><td>Item 2</td></tr>
<tr><td>Item 3</td></tr>
<tr><td>Item 4</td></tr>
<tr><td>Item 5</td></tr>
<tr><td><a>1</a>
<a>2</a>
<a class="a3">3</a>
</td></tr>
</tbody>


I want to set the opacity to 0.5 except the third anchor tag in the last
<td>
. How to set?

Answer
var atd = $('.a3').closest('td')
$("td").not(atd).addClass('opacity')//add class here

You can add a class with the specific css

Demo

Set opacity to child of td except class a3

Demo

Use .each()

Description: Iterate over a jQuery object, executing a function for each matched element.

To find match then add the class

Demo

var atd = $('.a3')
$("td").each(function(index) {
console.log($(this).find('a').length)
  if ($(this).find('a').length > 0) {
    $(this).children().not(atd).addClass('opacity') //add class here
  } else {
    $(this).addClass('opacity') //add class here
  }
})
.opacity {
  color: red;
  opacity: .5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody id="items">
    <tr>
      <td>Item 1</td>
    </tr>
    <tr>
      <td>Item 2</td>
    </tr>
    <tr>
      <td>Item 3</td>
    </tr>
    <tr>
      <td>Item 4</td>
    </tr>
    <tr>
      <td>Item 5</td>
    </tr>
    <tr>
      <td><a>1</a>
        <a>2</a>
        <a class="a3">3</a>
      </td>
    </tr>

</table>

Comments