简体   繁体   中英

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

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

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.

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

How can I detect the dynamically generated div?

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 .

One options is to use a custom event as a 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');
});

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");
});

How you inserting your dynamic generated 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 .

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):

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

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

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:

<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 div button and you'll get false . Add the div by clicking the Add div button and check again—you'll get true .

is very simple as that

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

}

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM