2011-08-29 30 views
5

我想檢查一個元素是否存在於整個頁面中。有什麼辦法通過jQuery知道元素是否存在於頁面中?查找元素是否存在於整個html頁面

例如:

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

在上面的代碼中,我要檢查的id <p>PARA1是否在DOM存在與否。在任何情況下,如果在'class'屬性的幫助下我們可以知道元素是否存在,那也是有幫助的。

回答

9

對於元素ID:

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

對於元素類:

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

最近我遇到了同樣的問題&這是爲我好。

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'); 
} 
相關問題