0

In my HTML, one div block(whose id looks like kdsm_32532535) is dynamically created after about 15-20 seconds of dom loading. I want to style this block with javascript with below code.

<script type="text/javascript">
$(document).ready(function(){

if($("div[id^='kdsm_']").length > 0){ 
  $(this).css({'margin':'20px','border':'1px dotted red;'});
}
  /* OR below code. None of them working :( */     
  $("div[id^='kdsm_']").css({'margin':'20px','border':'1px dotted red;'});
});
</script>

If I would do this in document.ready, it will not work because this div block doesn't exist on DOM ready.

How do i check continuously within interval of fraction, whether this div block is loaded or not ?

Umesh Patil
  • 10,475
  • 16
  • 52
  • 80

3 Answers3

1

You should call this method in script, that puts new block to DOM. OR use the setInterval method:

function applyCss(){

if($("div[id^='kdsm_']").length > 0){ 
  $(this).css({'margin':'20px','border':'1px dotted red;'});
}
  /* OR below code. None of them working :( */     
  $("div[id^='kdsm_']").css({'margin':'20px','border':'1px dotted red;'});
}

var interval = setInterval('applyCss()',2000);

If you want to stop this interval:

window.clearInterval(interval)
kaz
  • 1,943
  • 1
  • 13
  • 19
  • new block is placed by J2EE engine. Java script don't have control over it – Umesh Patil Jan 04 '12 at 11:11
  • I don't know J2EE but you should have an option to bind to the event, when this code is placed. – kaz Jan 04 '12 at 11:13
  • you can try also detecting DOM changes in particular subtrees using one of these methods: http://stackoverflow.com/questions/1091661/detect-element-content-changes-with-jquery – kaz Jan 04 '12 at 11:14
  • about css classes: you can add for each div same class like
    in style: .someclass { margin: 20px; border: 1px dotted red;}
    – kaz Jan 04 '12 at 11:22
1

You can set a common class for these dynamically created divs, so the CSS rules will be applied automatically, like that:

.kdsm_divs { margin:20px, border: 1px dotted red; }

Or you can use the .ready() method that will check for DOM state. Try this:

$("div[id^='kdsm_']").ready(function () {
  $("div[id^='kdsm_']").css({'margin':'20px','border':'1px dotted red;'});
});
Karlisson
  • 520
  • 4
  • 12
0

What about using style sheets?

You probably know the context where the divs will be placed so you can set up a style rule and let the browser apply the styles automatically.

Tom Hubbard
  • 15,820
  • 14
  • 59
  • 86