javascript(jquery)中判断一个元素在页面中是否存在的方法(转载来自CSDN)

在通过js获取页面元素时,常会因为某个id所标识的元素不存在而报js脚本错误,大部分原因是页面中的元素发生的更改,而js中没有即时作对应的更改,或者是更改很麻烦(因为个别元素的原因)。因此在用js对某个元素的属性进行“操作”时,应先判断元素是否存在。

注意如下几种判断方法,根据实际情况选择使用:

1. 判断表单元素是否存在(一)

if("periodPerMonth" in document.theForm)  
{
  return true;  
}else{ 
  return false;
}

2. 判断页面元素是否存在

if(document.getElementById("XXX"))   
{
  //存在
}

3.  判断表单元素是否存在(二)

if(document.theForm.periodPerMonth)   
{
  //存在
}

或   

if(typeof(document.theForm.periodPerMonth)=="object")   
{
  //存在
}

4. 判断表单是否存在

if(document.theForm)   
{
  //存在
}

5.用Jquery写脚本

if ($("#someID").length > 0 ) { 
  //存在
  $("#someID").text("hi");
}



原文地址:https://www.cnblogs.com/jice/p/2323462.html