如何检查页面上是否已存在具有ID的对象?

时间:2011-05-19 01:37:02

标签: jquery jquery-selectors javascript

  

可能重复:
  Is there an “exists” function for jQuery

比如说你有div:

<div id="hello"></div>

你正在动态创建一个div:

<div id="hello"></div>

是否有一个可以在Jquery中使用的函数,它将检查页面上是否存在具有您要创建的ID的对象?

2 个答案:

答案 0 :(得分:14)

if (document.getElementById('hello')) {
    // yup, already there
}

或者,jQuery方式:

if ($('#hello').length) {
    // yup, already there
}

答案 1 :(得分:12)

对于jQuery方法,您可以使用

if($("#selector").length) {
    //object already exists
}