I want to add the .red-border
class to a #container
div and all <td>
s in the closest <tr>
.
But by using .closest() I only get the elements immediate parent <td>
.
Is there a way I can target all children of the closest <tr>
?
My code is below.
My current erroneous JS:
$('#myelement').closest('.container, tr td').addClass('red-border');
Obviously, this only targets 1 td
. I want to encompass all of them.
My HTML:
<div id="container">
<span class="myelement">element</span>
</div>
<table>
<tr>
<td></td>
<td><span class="myelement">element</span></td>
<td></td>
</tr>
</table>
Edit: normally I might use the .find()
function but this wouldnt work with the or
operator.
I hope this is what you are expecting. You need to iterate through each tr
and add red-border
class to its first td
with td:first
selector as below
$(document).ready(function() { $('#container').addClass('red-border'); $('tr').each(function(){ $(this).find('td:first').addClass('red-border'); }) })
.red-border{ border:red 2px solid; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <span class="myelement">element</span> </div> <table> <tr> <td>First row First TD</td> <td><span class="myelement">element</span> </td> <td></td> </tr> <tr> <td>Second row First TD</td> <td><span class="myelement">element</span> </td> <td></td> </tr> </table>
why do you want it in a single line? just split it to two, it will be simpler.
$('.myelement').closest('#container').addClass('red-border');
$('.myelement').closest('tr').find('td').addClass('red-border');
by the way, you called #myelement
when your tag had a class myelement
. It should be called using .myelement
. And the container is an id so #container
According to your structure you can go for this:
$(".myelement").parents("#container").addClass('red-border').siblings("table").find("tr").eq(0).children().addClass('red-border');
target the parent #container
using parents()
. This will give nothing for the span
inside td
. Then target its sibling table
and the first tr
by using eq(0)
.
Call class element using .myelement instead of #myelement
$('.myelement').closest('.container, tr td').css({"color": "red", "border": "2px solid red"});
or
$('.myelement').closest('.container, tr td').addClass('red-border');
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.