View Single Post
Old 12-24-2011, 12:19 AM   PM User | #5
Logic Ali
Regular Coder

 
Logic Ali's Avatar
 
Join Date: Sep 2010
Location: London
Posts: 959
Thanks: 0
Thanked 198 Times in 193 Posts
Logic Ali will become famous soon enoughLogic Ali will become famous soon enough
Quote:
Originally Posted by xelawho View Post
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>

Last edited by Logic Ali; 12-24-2011 at 12:51 AM..
Logic Ali is offline   Reply With Quote