[英]jQuery select all children of closest
I want to add the .red-border
class to a #container
div and all <td>
s in the closest <tr>
. 我想将.red-border
类添加到#container
div中,并将所有<td>
都添加到最近的<tr>
。
But by using .closest() I only get the elements immediate parent <td>
. 但是通过使用.closest(),我只能获得元素的直接父元素<td>
。
Is there a way I can target all children of the closest <tr>
? 有没有一种方法可以针对最接近的<tr>
所有子级?
My code is below. 我的代码如下。
My current erroneous JS: 我当前的错误JS:
$('#myelement').closest('.container, tr td').addClass('red-border');
Obviously, this only targets 1 td
. 显然,这仅针对1 td
。 I want to encompass all of them. 我想涵盖所有这些。
My HTML: 我的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. 编辑:通常我可能会使用.find()
函数,但这不能与or
运算符一起使用。
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 你需要通过每个迭代tr
,并添加red-border
类的第一个td
与td:first
选择如下
$(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
. 顺便说一句,当标签具有class myelement
时,您调用了#myelement
。 It should be called using .myelement
. 应该使用.myelement
来调用它。 And the container is an id so #container
容器是一个ID,所以#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()
. 使用parents()
定位父#container
。 This will give nothing for the span
inside td
. 这对于td
内的span
没有任何帮助。 Then target its sibling table
and the first tr
by using eq(0)
. 然后使用eq(0)
定位其兄弟table
和第一个tr
。
Call class element using .myelement instead of #myelement 使用.myelement而不是#myelement调用类元素
$('.myelement').closest('.container, tr td').css({"color": "red", "border": "2px solid red"});
or 要么
$('.myelement').closest('.container, tr td').addClass('red-border');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.