Home >Web Front-end >JS Tutorial >Two solutions for JQuery to determine whether HTML elements exist_jquery
I encountered a situation at work. Some HTML elements on the page are controlled by server-side language to display different content according to different situations. However, in some cases on the same page, Ajax and services need to be used after the DOM is ready. End-to-end communication, and in some cases it is not needed, then I only want to trigger the Ajax part when the page contains the HTML tag I specified. After all, this can reduce the burden on the server. It’s a lot of nonsense. Let’s get to the point:
In fact, the method to solve the problem of JQuery determining whether an element exists is very simple:
if($("#abc").length >0) { ... }
if($("#abc").html() != "") { ... }
The above two methods can determine whether the HTML document contains the element we want. I have tried using $("#abc") != null / !$("#abc") / $.find("# abc") ..... The result does not work, because Object will be returned regardless of whether the element exists, so I have temporarily solved the problem by using one of the two methods above. Is there a better way to be discovered?