查找元素是否存在于整个html页面中

时间:2011-08-29 07:03:25

标签: javascript jquery html

我想检查整个页面中是否存在元素。有没有办法通过jQuery知道元素是否存在于页面中?

例如:

<html>
     <body>
        <p id="para1" class="para_class"></p>
     </body>
</html>

在上面的代码中,我必须检查DOM中是否存在id para1 <p>。在任何情况下,如果借助'class'属性,我们可以知道元素是否存在,它也会有所帮助。

2 个答案:

答案 0 :(得分:9)

对于元素ID:

if($('#para1').length){
  //element with id exists
}

对于元素类:

if($('.para_class').length){
  //element with class exists
}

答案 1 :(得分:0)

最近我遇到了同样的问题&amp;这对我有好处。

if ( $('#para1').lenght == 1 ){ // if the id exists its length will be 1 

      alert('This Id exists');

} elseif ( $('#para1').lenght == 0 ){ // if the id doesn't exists its length will be 0

      alert('This Id does not exists');
}