First off, I'm new to JS. So, I have a sample JS here.
<script>
function main(){
code_that_add_contents_to_dom();
code_that_works_on_added_contents_on_dom();
}
</script>
I am working on a web project where the situations usually occur above. Suppose the following functions.
var code_that_add_contents_to_dom = function(){
var parent = document.getElementById("id_1");
var child = document.createElement('div');
child.id = 'child_id_1';
parent.appendChild(child);
...
}
The above function adds new elements to dom and assumes there are many appendChild statements. Now let's create a function that works on those elements that were added to the DOM using the above function. For example, suppose we create a dataTable in this same element.
var code_that_works_on_added_contents_on_dom = function(){
var dataTable = $('#child_id_1').dataTable();
}
Now suppose I called the main () function. The problem is that the second function generates an error or does nothing at all. But if I write the main function, as shown below:
<script>
function main(){
code_that_add_contents_to_dom();
setTimeout(function(){
code_that_works_on_added_contents_on_dom();
},some_millisecs);
}
</script>
some_millisecs , 500 ( ), .
, .
, DOM. , . , dataTable (Bootstrap) JSON. code_that_add_contents_to_dom(); JSON
<table id='example'>
<thead>
<tr>
<th>Name</th>
<th>Position</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
</tr>
<tr>
<td>Roxi</td>
<td>System Admin</td>
</tr>
</tbody>
</table>
code_that_works_on_added_contents_on_dom(); div.
, , dataTable, " ". setTimeOut, .
, dataTable.addRow(). , DOM , DOM? , .
!!