I current have this:
<table>
<tbody>
<tr>
<td>
<a href="http://www.google.com">Visit Website</a>
</td>
</tr>
<tr>
<td>
<a href="">Visit Website</a>
</td>
</tr>
<tr>
<td>
<a href="http://www.google.com">Visit Website</a>
</td>
</tr>
<tr>
<td>
<a href="">Visit Website</a>
</td>
</tr>
</tbody>
</table>
I need some javascript that will:
if <a>
has no href (href="") then hide the TR that wraps it.
How do I achieve this using javascript?
You can use attribute equals selector for getting a
tag with href=""
and then get tr
by closest()
$('a[href=""]').closest('tr').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tbody> <tr> <td> <a href="http://www.google.com">Visit Website</a> </td> </tr> <tr> <td> <a href="">Visit Website</a> </td> </tr> <tr> <td> <a href="http://www.google.com">Visit Website</a> </td> </tr> <tr> <td> <a href="">Visit Website</a> </td> </tr> </tbody> </table>
Or you can use :has()
or has()
and attribute equals selector .
$('tr:has(a[href=""])').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tbody> <tr> <td> <a href="http://www.google.com">Visit Website</a> </td> </tr> <tr> <td> <a href="">Visit Website</a> </td> </tr> <tr> <td> <a href="http://www.google.com">Visit Website</a> </td> </tr> <tr> <td> <a href="">Visit Website</a> </td> </tr> </tbody> </table>
If you want to select a
tag without href
attribute then you can use :not()
selector, eg:
$('a[href=""],a:not(a[href])').closest('tr').hide();
simply try
$('a[href=""]').parent().parent().hide();
or
$('a[href=""]').closest("tr").hide();
simply try
$('a[href=""],a:not([href])').parent().parent().hide();
or
$('a[href=""],a:not([href])').closest("tr").hide();
https://jsfiddle.net/现在看看它的工作情况,请检查
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.