Home  >  Article  >  Web Front-end  >  jquery determines whether the node exists

jquery determines whether the node exists

藏色散人
藏色散人Original
2020-12-08 10:31:142830browse

The method for jquery to determine whether a node exists: first add an exist method to the jquery prototype; then determine the length attribute of the current object within the method; and finally use "$('#id').exist()" Just call it.

jquery determines whether the node exists

The operating environment of this tutorial: windows7 system, jquery1.10.0 version, thinkpad t480 computer.

Recommended: "jquery video tutorial" "javascript basic tutorial"

jQuery determines whether the DOM node exists in the page

1. First add an exist method to the jquery prototype;

2. Then determine within the method whether the length property of the current object is greater than 0. If it is greater than 0, it exists;

3. Finally, use $(' Just call #id').exist().

Add prototype:

(function($) {
 $.fn.exist = function(){ 
  if($(this).length>=1){
   return true;
  }
  return false;
 };
})(jQuery);

Usage method:

If the page has the following DOM nodes

<div id="a">这里是id=a节点</div>
<div>这里是DIV节点</div>
<div>这里是DIV节点</div>
<span>这里是span节点</span>

Judgement:

alert($( '#aaa').exist()); // false

alert($('#a').exist()); // true

alert($('div ').exist()); // true

alert($('p').exist()); // false

The above is the detailed content of jquery determines whether the node exists. For more information, please follow other related articles on the PHP Chinese website!

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