Home > php教程 > PHP开发 > body text

jQuery checks whether an element exists on the page

高洛峰
Release: 2016-12-08 15:07:16
Original
1164 people have browsed it

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) {
  //元素存在时执行的代码
}
Copy after login

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";
}
Copy after login

  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")) {
  //永远执行,不管元素是否存在
}
Copy after login

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


Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template