7

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?

Praful Bagai
  • 16,684
  • 50
  • 136
  • 267

5 Answers5

11

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');
});
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • What does path to content means? – Praful Bagai Sep 11 '13 at 03:57
  • @user1162512 It's just a sample URL path. You mentioned in a comment that the `
    ` is written in Python, so assumed Ajax was involved in retrieving it.
    – Jonathan Lonowski Sep 11 '13 at 03:59
  • No. Ajax is not involved in this particular case. I'm just forwarding this string of HTML elements onto the template when the page first loads or if I refresh the page. This is how I 'm doing. `return render_to_response('dashboard/widget_dashboard.html',{'HTMLstr':HTMLstr}, context_instance = RequestContext(request))` and in the template I'm calling that string of HTML elements by `{% if HTMLstr %} {% autoescape off %}{{ HTMLstr }}{% endautoescape %} {% else %}` – Praful Bagai Sep 11 '13 at 04:08
3

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");
});
Álvaro Martínez
  • 1,047
  • 7
  • 10
  • 1
    Test whenever you want to check if it exists. `$(function() {...})` is executed after the DOM has been loaded. If you add an element later, you must run the test again. (Not necesarily on a click event) – Álvaro Martínez Sep 11 '13 at 01:02
  • why was this downvoted? It look slike it's just an example of an event listener – Kai Qing Sep 11 '13 at 01:04
0

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.

R P
  • 33
  • 1
  • 6
Rameez
  • 1,712
  • 2
  • 18
  • 39
  • Well, I'm already aware of this, but I'm not creating the div in the jQuery but in the python(backend). Here is how I'm doing. `portlet_div_str += "
    – Praful Bagai Sep 11 '13 at 00:58
  • 2
    but how you adding it in document? without adding you can't check if its exist or not. – Rameez Sep 11 '13 at 01:02
  • I call it in the template using django syntax `{{{% autoescape off %}{{ portlet_div_str }}{% endautoescape %}}}` – Praful Bagai Sep 11 '13 at 01:03
0

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • 1
    Just love those drive–by down votes. Ok, no jQuery (hence "just for interest"), but what else? – RobG Sep 11 '13 at 06:03
0

is very simple as that

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

}

or

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