beginner beginner - 3 months ago 9
Ajax Question

why $(element) not works directly. but works in function

When i try to select any element which is the result of ajax call it don't get selected using

$(element)

but when i try to select that element in any function it will selected

Example: if i select an element with id
change
.

hello.php
is

<?php
echo '<span id="change"> hello </span>';
?>


html in
main.php
is

<div id="content">
</div>


and script in main.php

<script>
$.post("hello.php",function(r,s){$("#content").html(r)});
$("#change").css({"backgroundColor":"red"});
</script>


this script don't change the color of span , I know it will not work because at the time when 2nd statement is executed their was no element with id
change
,
and
$("#element")
can't find the element with id
change


But when i try
$("#change")
in any function it will change the color of span.
for example if i use

<script>
$.post("hello.php",function(r,s){$("#content").html(r)});
setTimeout(function(){$("#change").css({"backgroundColor":"red"});},0);
</script>


Please note i set the delay time to 0 sec. But this works and change the color of span with id
change
. I mean now the
$("#change")
can find the element with id
#change


and if i use $("#change") in ajax function then also it works.

<script>
$.post("hello.php",function(r,s){$("#content").html(r)});
$.post("example.php",function(r,s){$("#change").css({"backgroundColor":"red"});});
</script>


Can someone explain why this happen , why in other two examples
$("#change")
selects the element. even their is no delay in executing the function

Answer

This is due to the asynchronous nature of your post command. The rest of the script doesn't get halted till the post get finished. Rather than that, it get's executed even though the post command is already under progress. What you do with the timeout function is that you delay the execution of the jquery selection by a fraction of time, and this gives the time for the post to finish.

Comments