jquery判断元素是否存在

 时间:2026-04-29 17:54:02

平时在开发过程中。尤其,是前端工程师需要找到页面某个元素,然后对它进行操作。如果,是空元素就会报错。

传统javascript,写法是:

       document.getElementById("id").innerText("hello");

        如果id元素不存在,页面会报错:document.getElementById("id") is null

正确写法:

     obj = document.getElementById("id");     if (obj){       obj.innerText("hello");      }

jquery写法:

      if ($("#id")){        $("#id").text("hello");       }

这是错误的,因为jquery对象永远都有返回值。

正确写法:

     if ( $("#id").length > 0 ) {      $("#id").text("hello");       }

其实,jquery不需要判断页面某个元素是否存在,它本身会忽略不存在元素进行操作,也不会报错。

  • jquery如何查找空元素
  • jquery如何定位到元素
  • 如何使用jQuery中的has方法判断元素包含元素
  • 什么是jquery
  • 元素神殿怎么打
  • 热门搜索
    微信怎么加群 抬头纹怎么去除 雪里红的做法 酱猪蹄的做法 孕妇鲫鱼汤的做法 羊腰子的做法 怀孕怎么算时间 焖面的做法 凉拌粉丝的家常做法 蔬菜沙拉的家常做法