... oder etwas kompakter:
<script>
for (var i=1; i<9; i++) {
var bild = document.getElementById('bild'+i)
if (bild.style.display == 'none') {
bild.parentNode.removeChild(bild)
} else {
bild.firstChild.setAttribute('alt', '#htmlcaption' + i)
}
}
</script>