JQUERY Change TD style ONLY IF IT contains input t

2019-07-23 03:07发布

I have applied a style as follows and it works great for me:

$("td[id='cellId']").css("text-align", "left");

However, I need that style to only be applied to the TD IF it contains textboxes and NOT radio buttons.

I have searched hi and low, but find(), contains() and the likes, does not seem to be working.

3条回答
我想做一个坏孩纸
2楼-- · 2019-07-23 03:21

If you need to filter TD-s which contain textboxes and NOT radio buttons, then you need to use :has and :not combination:

 $("td:not(:has(input[type='radio']))").has("input[type='text']").css("background", "red");

Here is a snippet where filtered cells got a red background. You can apply any style to them.

$("td:not(:has(input[type='radio']))").has("input[type='text']").css("background", "red");
td {
    border: 1px solid green;
    padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
 <tr>
  <td><input type="text">cell-1-1</td>
  <td><input type="radio">cell-1-2</td>
  <td><input type="text"><input type="radio">cell-1-3</td>
 </tr>
 <tr>
  <td><input type="radio">cell-2-1</td>
  <td><input type="text">cell-2-2</td>
  <td>cell-2-3</td>
 </tr>
</table>

查看更多
孤傲高冷的网名
3楼-- · 2019-07-23 03:22

First note that your $("td[id='cellId']") is rather surprising: I may guess that you have some var cellId which contains the cell id, so you should use $('#' + cellId).

Now, since you didn't precise about the (eventually) nested elements in the td, we must ensure there is no radio button inside it.
Anyway let's suppose we have var cellElem that you've populated as needed (may be like showed above).

So you may use something like this:

if (!cellElem.find([type=radio]).length) {
    cellElemn.css(textAlign: 'left');
}
查看更多
做自己的国王
4楼-- · 2019-07-23 03:33

Use the :has() selector to match elements that contain other elements.

$("td#cellId:has(:text)").css("text-align", "left");
查看更多
登录 后发表回答