Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 554
PythonEnthusiast Avatar asked Sep 11 '13 00:09

PythonEnthusiast


2 Answers

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');
});
like image 122
Jonathan Lonowski Avatar answered Sep 30 '22 19:09

Jonathan Lonowski


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");
});
like image 43
Álvaro Martínez Avatar answered Sep 30 '22 21:09

Álvaro Martínez