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

Tay*_*Mac 20 javascript jquery jquery-selectors

可能重复:
jQuery是否存在"exists"函数

比如说你有div:

<div id="hello"></div>
Run Code Online (Sandbox Code Playgroud)

而且你正在动态创建一个div:

<div id="hello"></div>
Run Code Online (Sandbox Code Playgroud)

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

dec*_*eze 14

if (document.getElementById('hello')) {
    // yup, already there
}
Run Code Online (Sandbox Code Playgroud)

或者,jQuery方式:

if ($('#hello').length) {
    // yup, already there
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*arz 14

对于jQuery方法,你可以使用

if($("#selector").length) {
    //object already exists
}
Run Code Online (Sandbox Code Playgroud)