<html>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$("div.block").each(index){
this.text('Fill this writing of divs with the classname "block"')}
</script>
<body>
<div>Not here</div>
<div class='block'>replace me -- not working, why?</div>
<div>Not here</div>
<div class='block'>replace me -- not working, why?</div>
</body>
</html>
Asked
Active
Viewed 3,893 times
0

hhh
- 50,788
- 62
- 179
- 282
1 Answers
4
You don't need to use each - you can just call the text method on your entire selection:
$("div.block").text('Fill this writing of divs with the classname "block"');
Incidentally, your problem above was that you were using each incorrectly
$("div.block").each(function(index, el){
$(el).text('Fill this writing of divs with the classname "block"');
});

Adam Rackis
- 82,527
- 56
- 270
- 393
-
1Those dom elements are not ready when the script runs. You need to wrap that script in a document.ready handler, OR move the script to the very end of you body. – Adam Rackis Nov 22 '12 at 23:41
-
...suppose I would like to fill the div with many of this kind of things `
` so array `values={{'happy.png','I am happy'}, {'happy2.png', 'I am also happy'}, {'hello.png', 'It is hello'}}`. How would you iterate it? – hhh Nov 22 '12 at 23:47I am happy -
@hhh - I'm afraid I don't follow. I'd recommend you write up a new question and fully explain what you're trying to do. – Adam Rackis Nov 22 '12 at 23:49
-
Yes Sir, [here](http://stackoverflow.com/questions/13521639/images-and-text-from-array-into-divs-with-jquery). – hhh Nov 23 '12 at 00:13