如何使用子元素的 ID 选择父元素的第一个子元素

How to select first child of parent by using ID of a child element?

本文关键字:元素 第一个 选择 ID 何使用      更新时间:2023-09-26

我尝试选择包含"Text1"的td元素,而不给这个td元素一个ID。所以"Text1"最后应该有红色的背景色。我试过这样,但这不起作用。

$("#test").parent().closest("td").css("background-color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
  <td>
    <p>
    Text1
    </p>
  </td>
  <td id="test">
    <p>
    Text2
    </p>
  </td>
</tr>
</table>

https://jsfiddle.net/8wyuggxz/

您可以使用

prev()方法,如下所示。

$("#test").prev('td').css("background-color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td>
            <p>
                Text1
            </p>
        </td>
        <td id="test">
            <p>
                Text2
            </p>
        </td>
    </tr>
</table>

编辑:这是一个使用 ID 的 JS 解决方案:

看到这个工作小提琴

$("#test").parent().find("td:first-child").css("background-color", "red");

尝试如下:

$("#test").parent().children("td:nth-child(1)").css("background-color", "red");

工作代码笔:http://codepen.io/anon/pen/wGMZYG

使用:contains选择器

$('td:contains("Text1")').css("background-color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <p>
        Text1
      </p>
    </td>
    <td id="test">
      <p>
        Text2
      </p>
    </td>
  </tr>
</table>

    如何使用子元素
  1. 的ID选择父元素的第一个子元素?

  2. 我尝试选择包含"Text1"的 td 元素

这两个查询的解决方案。

代码片段:

$("#test").parent().children('td:first:contains("Text1")').css("background-color", "red");

小提琴演示