views:

38

answers:

2

Hi, I have this code.

<div id="static_element"></div>

<script>
   $(document).ready(function()
   {
      $("#static_element").html("<b class="dynamic_element">Test</b>");

      //this row wont work
      $(".dynamic_element").css({"color":"red"});
   })
</script>

i want to access the tag "b" with the class "dynamic_element" but i cant because it was dynamically generated.

Any ideas? Thanks

+1  A: 

This:

$("#static_element").html("<b class='dynamic_element'>Test</b>");

will work. It doesn't matter that the element is generated by script, jQuery selectors will match all elements that are present in the DOM at the time they are called. The only culprit is with Ajax functions, like load. Elements added to the DOM with these methods do not appear the time the methods are called, but asynchronously, when the request is completed. Luckily, there are callbacks that you can use for such cases.

kgiannakakis
A: 

you are generating the html the wrong way. Always put html in single quotes so that the double quotes wont break it:

 $("#static_element").html('<b class="dynamic_element">Test</b>');
RJD22
i wanted to make things clearer but I should give the wide picture.the dynamic data comes from ajax with datatype "html".In the success function i place the item that came back from the ajax inside the static html.$("#space").html(data_from_ajax);//<div><bid="sub_dinamic_element">Test</b></div>after a while, in a different onclick event i try to access it.$("#sub_dinamic_element").css(....);Thanks
fatnjazzy
where does that onclick event happen? inside the generated html?
RJD22
Are you sure that this element is actually present in the data returned from ajax? Also, could you possibly use the `$("#space").load(url);` instead of manually issuing the ajax request and setting the html() ?
Graza