Quote:
Originally Posted by xelawho
Code:
<script type="text/javascript">
function changeDivs() {
var divs = document.getElementsByTagName("div")
for(var j = 0; j<divs.length; j++){
document.getElementById('myid'+j).style.width= 200+"px";
}
}
</script>
</body>
|
That's rather fragile in that it breaks if any other unrelated divs are added to the page. Better to test the presence of IDs in the expected sequence.
Code:
<script type="text/javascript">
function changeDivs()
{
for( var j = 0, elem; ( elem = document.getElementById( 'myid' + j ) ); j++ )
elem.style.width = parseInt( elem.style.width ) + 200 + "px";
}
</script>
Actually this can be made more robust by removing the need for all IDs in the sequence to be present, simply by testing all divs for the right ID format:
Code:
<script type="text/javascript">
function changeDivs()
{
var divs = document.getElementsByTagName( "div" );
for( var j = 0, elem; ( elem = divs[ j ] ); j++ )
{
if( /^myid\d+/.test( elem.id ) )
elem.style.width = parseInt( elem.style.width ) + 200 + "px";
}
}
</script>