How to check if element with id in jQuery exists?

I am generating a div dynamically, and I have to check if a dynamically generated div exists or not? How can i do this?

I am currently using the following which does not detect a dynamically generated div. It discovers that there is already an element with the identifier contained in the HTML template.

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

How can I detect a dynamically generated div?

+6
source share
5 answers

If mutation monitoring is not a choice due to browser compatibility , you will have to include code that actually inserts a <div> into the document .

One option is to use a custom event in the form of 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'); }); 
+10
source

If it is added dynamically, you need to test again. Let's say the click event

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

How do you insert your dynamic generated div?

It works if you do it like this:

 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

0
source

Just for fun, you can also use a live collection for this (they are provided as part of the DOM). You can set up a collection of all divs on the page (this can be done in the head before loading the body):

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

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

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

If the identifier is not a valid identifier or is held in a variable, use a square bracket notation. Some replay codes:

 <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" button and you will get false . Add the div by clicking the "Add div" button and check again: you will get true .

0
source

very simple since

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

or

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

Source: https://habr.com/ru/post/953596/


All Articles