检查是否存在具有特定ID的div

时间:2011-05-13 23:06:33

标签: javascript jquery

我有一个字符串,我需要检查页面中是否有一个div = id = my string。

我如何用jquery做到这一点?

像:

if (isset $(mystring))
 // do somethinhg

4 个答案:

答案 0 :(得分:5)

if ($("#" + mystring).length > 0)
  alert(mystring + " exists!");
else
  alert("element with id " + mystring + " does not exist..");

将此代码放在页面底部或包含在$(document).ready()函数内,否则即使页面中的元素存在,也无法识别。

答案 1 :(得分:2)

我会选择:

if ( $('#' + mystring)[0] ) {

答案 2 :(得分:1)

不需要jQuery来执行此操作。在本地js中:

if (document.getElementById("mystring")) {
   alert("exists");
}

答案 3 :(得分:0)

您可以使用is()功能执行此操作。 http://api.jquery.com/is/

以下是一个简单示例:http://jsfiddle.net/hRLgw/

相关问题