JS native to determine whether the DOM node exists in the page
JavaScript native functions do not provide a way to determine whether a DOM node exists, and we typically get DOM nodes almost all document.getelement. method returns an object combination set, which we can use to access each object of the collection by Object[0],object[1. Now that you are returning a combination set of numbers, you have the length property, and length greater than or equal to 1 indicates that the DOM node exists in the page
Code:
Object.prototype.exist = function () {
if (typeof this!= ' undefined ' && this.length>=1) {return
true;
}
return false;
Use:
Suppose the page has the following nodes
<div> here is div node </div>
<div> here is div node </div>
<span> Here is span node </span>
To determine whether a node is on a page:
var is_exist = document.getelementsbytagname (' div '). exist ();
alert (is_exist); True
var is_exist = document.getelementsbytagname (' span '). exist ();
alert (is_exist); True
var is_exist = document.getelementsbytagname (' P '). exist ();
alert (is_exist); False
Note: If you use the document.getElementById () method to get an object, you cannot use the exist () method, because the method that takes the node object by ID returns an empty object without the node being integrated, and does not integrate the prototype exist () function, so it will be an error! So if the object is based on an ID, it can be directly if (obj) to determine whether the DOM node exists in the page
jquery determines whether a DOM node exists in the page
You can do that.
To add a prototype:
(function ($) {
$.fn.exist = function () {
if ($ (). length>=1) {return
true;
}
return false;}
) (JQuery);
How to use:
If the page has the following DOM node
<div id= "A" > here is id=a node </div>
<div> here is div node </div>
<div> here is div node </div>
<span> This is the span node </span>
Judge:
Alert ($ (' #aaa '). exist ()); False
Alert ($ (' #a '). exist ());//True
alert ($ (' div '). exist ());//True
alert ($ (' P '). exist ());//False
In fact, both of the above methods are based on the length property of the object set to determine whether the object exists.
This article is a small series of js/jquery to judge whether the DOM node exists simple method of all content, I hope that we support cloud-Habitat Community ~