如何获取 div Jquery 的所有后代子代

dan*_*era 1 jquery

我需要获取 div en Jquery 的所有后代子项,不仅是直接子项 我需要属性 css 应用于元素 p 和元素跨度

<!DOCTYPE html>
<html>

<head>
  <style>
    .descendants * {
      display: block;
      border: 2px solid lightgrey;
      color: lightgrey;
      padding: 5px;
      margin: 15px;
    }
  </style>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $("div").children().css({
        "color": "red",
        "border": "2px solid red"
      });
    });
  </script>
</head>

<body>

  <div class="descendants" style="width:500px;">div (current element)
    <p>p (child)
      <span>span (grandchild)</span>
    </p>
    <p>p (child)
      <span>span (grandchild)</span>
    </p>
  </div>

</body>

</html>
Run Code Online (Sandbox Code Playgroud)

j08*_*691 9

而不是.children()(只会得到......等待......元素的孩子)使用 .find('*')

$(document).ready(function() {
  $("div").find('*').css({
    "color": "red",
    "border": "2px solid red"
  });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="descendants" style="width:500px;">div (current element)
  <p>p (child)
    <span>span (grandchild)</span> 
  </p>
  <p>p (child)
    <span>span (grandchild)</span>
  </p>
</div>
Run Code Online (Sandbox Code Playgroud)