Home >php教程 >PHP开发 >jQuery checks whether an element exists on the page

jQuery checks whether an element exists on the page

高洛峰
高洛峰Original
2016-12-08 15:07:161178browse

I recently worked on a project, and there is a function to use jQuery to check whether a certain element exists on the web page. I record it here, it may help friends who are reading the article.

When using jQuery to check whether an element exists on the web page, you should judge based on the length of the element obtained. The code is as follows:

if($("#tt").length > 0) {
  //元素存在时执行的代码
}

The specific reasons are as follows:

In JavaScript, we are using the traditional getElementById () and getElementsByTagName(), if the relevant element cannot be found in the web page, the browser will report an error, which will affect the execution of subsequent code. Therefore, in order to avoid browser errors, you can judge the element, for example:

if(document.getElementById("tt")) {//js判断元素是否存在
  document.getElementById("tt").style.color = "red";
}

  If there are many elements to be operated, it will require a lot of repetitive work, which is often tiring. One of the advantages of jQuery is its complete processing mechanism. Even if jQuery is used to obtain elements that do not exist in the web page, no error will be reported. This is because $("#tt") always obtains an object, even if there is no such element on the web page. Therefore, when you want to use jQuery to check whether an element exists on the web page, you cannot use the following code:

if($("#tt")) {
  //永远执行,不管元素是否存在
}

 This is why you need to judge whether an element exists on the page based on its length.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn