使用 jQuery 检查元素是否存在

有两种方法可以使用 jQuery 来检查元素是否存在,一种是 length 属性,另一种是使用方法来创建我们自己的 exist() 方法。本教程演示如何检查元素是否存在。

使用 jQuery 使用 Length 属性检查元素是否存在

jQuery 的 length 属性可用于检查元素是否存在;它返回总匹配元素。如果 length 返回 0,则元素不存在,其他任何值表示元素存在。

length 属性的语法是:

($("element").length)

上面的语法将返回 0 或任何其他数字。

让我们尝试一个示例,通过使用 length 属性来检查元素是否存在。参见示例:

<!DOCTYPE html>
<html>
<head>
    <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
    <title>jQuery Length</title>
    <style>
    body {
        text-align: center;
    }
    h1 {
        color: lightblue;
        font-size: 4.5rem;
    }
    button {
        cursor: pointer;
        margin-top: 4rem;
    }
    </style>
</head>
<body>
    <h1>Delftstack | The Best Tutorial Site</h1>
    <p id="DemoPara1">This is paragraph 1</p>
    <button id="DemoButton1"> Check Paragraph 1</button>
    <button id="DemoButton2"> Check Paragraph 2 </button>
    <button id="DemoButton3"> Check Heading 1 </button>
    <script type="text/javascript">
    $(document).ready(function () {
        $("#DemoButton1").click(function () {
        if ($("#DemoPara1").length) {
            alert("Paragraph 1 exists");
        }
        else {
        alert("Paragraph 1 does not exist");
        }
        });
        $("#DemoButton2").click(function () {
        if ($("#DemoPara2").length) {
            alert("Paragraph 2 exists");
        }
        else {
            alert("Paragraph 2 does not exist");
        }
        });
        $("#DemoButton3").click(function () {
        if ($("h1").length) {
            alert("Heading 1 exists");
        }
        else {
            alert("Heading 1 does not exist");
        }
        });
    });
    </script>
</body>
</html>

上面的代码将通过按下不同的按钮来检查段落和标题是否存在。见输出:

使用 jQuery 检查元素是否存在

使用 jQuery 创建一个用户定义的函数来检查元素是否存在

现在,让我们尝试创建自己的方法来检查元素在 jQuery 中是否存在。存在创建函数的语法是:

jQuery.fn.exists = function () {
          return this.length > 0;
};

如你所见,我们使用 length 属性通过 jQuery 创建了我们自己的 exists 函数。length 属性用于返回元素的长度,而不是检查它们的存在;这就是为什么我们可以创建自己的方法一次并在任何地方使用它。

参见示例:

<!DOCTYPE html>
<html>
<head>
    <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
    <title>jQuery Exists</title>
    <style>
    body {
        text-align: center;
    }
    h1 {
        color: lightblue;
        font-size: 4.5rem;
    }
    button {
        cursor: pointer;
        margin-top: 4rem;
    }
    </style>
</head>
<body>
    <h1>Delftstack | The Best Tutorial Site</h1>
    <p id="DemoPara1">This is paragraph 1</p>
    <button id="DemoButton1"> Check Paragraph 1</button>
    <button id="DemoButton2"> Check Paragraph 2 </button>
    <button id="DemoButton3"> Check Heading 1 </button>
    <script type="text/javascript">
    $(document).ready(function () {
        jQuery.fn.exists = function () {
          return this.length > 0;
        };
        $("#DemoButton1").click(function () {
        if ($("#DemoPara1").exists()) {
            alert("Paragraph 1 exists");
        }
        else {
        alert("Paragraph 1 does not exist");
        }
        });
        $("#DemoButton2").click(function () {
        if ($("#DemoPara2").exists()) {
            alert("Paragraph 2 exists");
        }
        else {
            alert("Paragraph 2 does not exist");
        }
        });
        $("#DemoButton3").click(function () {
        if ($("h1").exists()) {
            alert("Heading 1 exists");
        }
        else {
            alert("Heading 1 does not exist");
        }
        });
    });
    </script>
</body>
</html>

上面的代码使用用户定义的函数 exists 来检查元素是否存在。输出将类似于示例一。

见输出:

使用 jQuery 检查元素是否存在

使用 JavaScript 检查元素是否为 Select 下拉列表

使用 tagName 属性检查元素是否是 select 下拉列表,例如 if (select.tagName === 'SELECT') {}。 tagName 属性返回访问它的元素的标签名称。 请注意,该属性以大写形式返回 DOM 元素的标记名称。

这是本文中示例的 HTML。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <select name="fruits" id="fruit-select">
      <option value="">--Choose an option--</option>
      <option value="apple">Apple</option>
      <option value="banana">Banana</option>
      <option value="kiwi">Kiwi</option>
    </select>

    <script src="index.js"></script>
  </body>
</html>

这是相关的 JavaScript 代码。

const select = document.getElementById('fruit-select');

if (select.tagName === 'SELECT') {
  console.log('✅ 元素是一个 select 下拉菜单');
} else {
  console.log('⛔️ 元素不是一个 select 下拉菜单');
}

tagName 属性返回访问它的元素的标签名称。

应该注意的是 DOM 元素名称是大写的。 例如,如果在 div 元素上访问,则 tagName 属性将返回“DIV”。

const select = document.getElementById('fruit-select');
console.log(select.tagName); // ?️ "SELECT"

我们可以使用 String.toLowerCase 方法将标签名称转换为小写。

const select = document.getElementById('fruit-select');

if (select.tagName.toLowerCase() === 'select') {
  console.log('✅ 元素是一个 select 下拉菜单');
} else {
  console.log('⛔️ 元素不是一个 select 下拉菜单');
}

这种方法更直观一点,因为我们的代码的读者可能会对大写的 SELECT 字符串感到困惑。

如果大家需要确保在访问 tagName 属性之前存储在 select 变量中的值不为 null 或 undefined,请使用可选链接。

const select = null;

if (select?.tagName?.toLowerCase() === 'select') {
  console.log('✅ 元素是一个 select 下拉菜单');
} else {
  console.log('⛔️ 元素不是一个 select 下拉菜单');
}

如果向 getElementById 方法提供不存在的 id 或向 querySelector 方法提供不存在的选择器,则可能会返回 null 值。

如果引用指向 null 值或 undefined 值,可选的链接 (?.) 运算符允许我们进行短路。

运算符短路返回 undefined,而不是抛出错误。

在上面的示例中,select 变量的值为 null,因此运行 else 块。