I have a situation where I need to add a class to a table, but only if the table is inside a div with id 'mydiv' AND there is a row in table containing an <a href=...> element where the href contains the term 'myref', including the quotes. Is this easy in jQuery and if so, how do I do this? I just can't work out how to change an element while referring forward and backwards to others.
I tried the following, but it doesn't seem to work (I am relatively new to jQuery, as you can probably see from the below):
$('.mydiv').find('td').find('a[href]').contains('myref').parent.parent.addClass('myclass')
The following html snippet simulates my situation (I cannot change the html, just add some javascript and css):
<div id='mydiv'>
<a href='blahblah'>Some text</a>
<table>
<tbody>
<tr>
<td><a href="some href">Some text</a></td>
<td><a href="javascript:some javascript containing 'myref' in quotes">Some text</a></td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><a href="some href">Some text</a></td>
<td><a href="javascript:some javascript without match">Some text</a></td>
</tr>
</tbody>
</table>
</div>
<div id='otherdiv'>
<table>
<tbody>
<tr>
<td><a href="some href">Some text</a></td>
<td><a href="javascript:some javascript containing 'myref' in quotes">Some text</a></td>
</tr>
</tbody>
</table>
</div>
The first table needs to get the new class, the second and third don't.
答案 0 :(得分:5)
要实现此目的,您可以使用has()
方法查找包含table
所需的a
元素以及包含&#39;属性的元素。选择器以href
获取myref
。试试这个:
$('#mydiv table').has('a[href*="myref"]').addClass('myclass');
答案 1 :(得分:1)
您搜索名为mydiv - $(".mydiv")
的课程,而不是搜索ID
像这样更改您的代码:)
$("#mydiv").find("td").find("a[href*='myref']").parents("table").addClass("myClass");
&#13;
.myClass {
background-color: lightblue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='mydiv'>
<a href='blahblah'>Some text</a>
<table>
<tbody>
<tr>
<td><a href="some href">Some text</a></td>
<td><a href="javascript:some javascript containing 'myref' in quotes">Some text</a></td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><a href="some href">Some text</a></td>
<td><a href="javascript:some javascript without match">Some text</a></td>
</tr>
</tbody>
</table>
</div>
<div id='otherdiv'>
<table>
<tbody>
<tr>
<td><a href="some href">Some text</a></td>
<td><a href="javascript:some javascript containing 'myref' in quotes">Some text</a></td>
</tr>
</tbody>
</table>
</div>
&#13;
答案 2 :(得分:0)
您可以在目标S3GetObjectRequest
上使用closest()
来查找其父级td
)。然后table
检查$.each()
表格中的每个td
和first
,以查找indexOf()
的具体文字。
代码段:
href
$(function() {
$('#mydiv table:first td').each(function() {
if ($(this).find('a').attr('href').indexOf('myref') != -1)
$(this).closest("table").addClass('myclass');
});
})
.myclass {
background-color: red;
}