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.