how to check for jQuery's FIND result

This question already has an answer here:

  • Check if element exists in jQuery [duplicate] 8 answers
  • Is there an “exists” function for jQuery? 36 answers

  • You were very close!

    Simply check for selected.length instead of selected .

    Demo for parent selection

    $(document).ready(function() {
      var parent = $(this).find(".parent");
      if (parent) {
        var selected = parent.find("div.selected");
        if (selected.length) {
          selected.css({
            "color": "blue",
            "border": "2px solid blue"
          });
        } else {
          parent.css({
            "color": "red",
            "border": "2px solid red"
          });
        }
      }
    });
    .ancestors * {
      display: block;
      border: 2px solid lightgrey;
      color: lightgrey;
      padding: 5px;
      margin: 15px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
    <script>
    </script>
    
    <div class="parent"> Parent Box
      <div class="noselected"> Box A </div>
      <div class="notselected"> Box B </div>
    </div>

    $(document).ready(function() {
      var parent = $(this).find(".parent");
      // check for the length property of the jquery object to get the number of elements matched
      if (parent.length != 0) {
        var selected = parent.find("div.selected");
        // same goes here
        if (selected.length != 0) {
          selected.css({
            "color": "blue",
            "border": "2px solid blue"
          });
        } else {
          parent.css({
            "color": "red",
            "border": "2px solid red"
          });
        }
      }
    });
    .ancestors * {
      display: block;
      border: 2px solid lightgrey;
      color: lightgrey;
      padding: 5px;
      margin: 15px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
    <div class="ancestors">
      <div class="parent"> Parent Box
        <div class="notselected"> Box A </div>
        <div class="notselected"> Box B </div>
      </div>
    </div>
    链接地址: http://www.djcxy.com/p/83694.html

    上一篇: 如果包含某些文本,则运行jquery

    下一篇: 如何检查jQuery的FIND结果