Reputation: 35
I'm trying to a add a class to every element that contains an <a>
with a text so I could hide the <tr>
's that has no text! here is my HTML code and JavaScript:
$("tr a").each(function () {
var a= $(e);
if ($e.text().length > 0) {
tr.addClass("buttoneffect");
}
});
table tr {
height: 36px;
}
table tr:hover {
background-color: #BEDB7F;
}
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td><a href="">Test 1</a></td>
</tr>
<tr>
<td><a href="">Test 2</a></td>
</tr>
<tr>
<td><a href=""></a></td>
</tr>
<tr>
<td><a href="">Test 4</a></td>
</tr>
<tr>
<td><a href=""></a></td>
</tr>
<tr>
<td><a href="">Test 6</a></td>
</tr>
</tbody>
</table>
Upvotes: 1
Views: 67
Reputation: 4637
Try this Demo Here
$("tr a").each(function () {
var a= $(this);
if (a.text().length > 0) {
a.closest('tr').addClass("buttoneffect");
}
});
Upvotes: 0
Reputation: 6031
use jquery parent().
$("tr a").each(function () {
var a= $(this);
if (a.text().length > 0) {
a.parnt('tr').addClass("buttoneffect");
}
});
Upvotes: 0
Reputation: 388316
You can use .filter() find filter those elements and then call .addClass() on the filtered set to add the class
$("tr").filter(function () {
return $(this).find('a').text().trim().length > 0
}).addClass("buttoneffect");
Demo: Fiddle
Upvotes: 0
Reputation: 15715
see this fiddle
first you are referencing e
, which you didn't pass inside the event callback, and there is no tr
directly accessible you have to find out the closest
tr
to that of a
$("tr a").each(function () {
var a= $(this);
if (a.text().length > 0) {
a.closest('tr').addClass("buttoneffect");
}
});
tr:not(.buttoneffect)
{
display:none;
}
$("tr a").each(function() {
var a = $(this);
if (a.text().length > 0) {
a.closest('tr').addClass("buttoneffect");
}
});
table tr {
height: 36px;
}
table tr:hover {
background-color: #BEDB7F;
}
.buttoneffect {
background: red;
}
tr:not(.buttoneffect) {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td><a href="">Test 1</a>
</td>
</tr>
<tr>
<td><a href="">Test 2</a>
</td>
</tr>
<tr>
<td>
<a href=""></a>
</td>
</tr>
<tr>
<td><a href="">Test 4</a>
</td>
</tr>
<tr>
<td>
<a href=""></a>
</td>
</tr>
<tr>
<td><a href="">Test 6</a>
</td>
</tr>
</tbody>
</table>
Upvotes: 2