如何检查带有 id 的元素在 jQuery 中是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18730896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:21:12  来源:igfitidea点击:

How to check if an element with id exists or not in jQuery?

javascriptjqueryhtml

提问by PythonEnthusiast

I'm generating a div dynamically and I've to check whether a dynamically generated div exists or not ? How can I do that?

我正在动态生成一个 div,我必须检查动态生成的 div 是否存在?我怎样才能做到这一点?

Currently I'm using the following which does not detects the div generated dynamically. It only detects if there is already an element with the id contained in the HTML template.

目前我正在使用以下不检测动态生成的 div。它只检测 HTML 模板中是否已经存在具有 id 的元素。

$(function() {
    var $mydiv = $("#liveGraph_id");
    if ($mydiv.length){
        alert("HHH");
    }
});

How can I detect the dynamically generated div?

如何检测动态生成的 div?

回答by Jonathan Lonowski

If mutation observes aren't an option due to their browser compatibility, you'll have to involve the code that's actually inserting the <div>into the document.

如果突变观察是不是一种选择,由于他们的浏览器兼容性,你必须包括这实际上是插入的代码<div>进入document

One options is to use a custom event as a pub/sub.

一种选择是使用自定义事件作为pub/sub

$(document).on('document_change', function () {
    if (document.getElementById('liveGraph_id')) {
        // do what you need here
    }
});
// without a snippet to go on, assuming `.load()` for an example
$('#container').load('/path/to/content', function () {
    $(this).trigger('document_change');
});

回答by álvaro Martínez

If it is added dinamically, you have to test again. Let's say, a click event

如果动态添加,则必须再次测试。比方说,一个点击事件

$("#element").click(function()
{
    if($("#liveGraph_id").length)
        alert("HHH");
});

回答by Rameez

How you inserting your dynamic generated div?

您如何插入动态生成的 div?

It works if you do it in following way:

如果您按以下方式进行操作,它会起作用:

var div = document.createElement('div');
div.id = 'liveGraph_id';
div.innerHTML = "i'm dynamic";
document.getElementsByTagName('body')[0].appendChild(div);
if ($(div).length > 0) {
    alert('exists'); //will give alert
}
if ($('#liveGraph_id').length > 0) {
    alert('exists'); //will give alert
}
if ($('#liveGraph_id_extra').length > 0) {
    alert('exists'); //wont give alert because it doesn't exist.
}

jsfiddle.

jsfiddle

回答by RobG

Just for interest, you can also use a live collection for this (they are provided as part of the DOM). You can setup a collection of all divs in the page (this can be done in the head even before the body is loaded):

出于兴趣,您也可以为此使用实时集合(它们作为 DOM 的一部分提供)。您可以设置页面中所有 div 的集合(这甚至可以在加载正文之前在头部完成):

var allDivs = document.getElementsByTagName('div');

Any div with an id is available as a named property of the collection, so you can do:

任何带有 id 的 div 都可用作集合的命名属性,因此您可以执行以下操作:

if (allDivs.someId) {
  // div with someId exists
}

If the ID isn't a valid identifier, or it's held in a variable, use square bracket notation. Some play code:

如果 ID 不是有效标识符,或者它保存在变量中,请使用方括号表示法。一些播放代码:

<button onclick="
  alert(!!allDivs.newDiv);
">Check for div</button>
<button onclick="
  var div = document.createElement('div');
  div.id = 'newDiv';
  document.body.appendChild(div);
">Add div</button>

Click the Check for divbutton and you'll get false. Add the div by clicking the Add divbutton and check again—you'll get true.

单击Check for div按钮,您将获得false. 单击Add div按钮添加 div并再次检查 - 您将获得true.

回答by user3510753

is very simple as that

很简单

   if(document.getElementById("idname")){
//div exists 

}

or

或者

    if(!document.getElementById("idname")){
//  don't exists
}