user2373912
user2373912

Reputation: 185

edit child div's height with javascript

I am working on an exercise that give me the following, and I want to change the heights and widths of the child divs with javascript, and without giving classes or divs to the inner divs

<div id="puzzlearea">
    <div>1</div>  <div>2</div>  <div>3</div>  <div>4</div>
    <div>5</div>  <div>6</div>  <div>7</div>  <div>8</div>
    <div>9</div>  <div>10</div> <div>11</div> <div>12</div>
    <div>13</div> <div>14</div> <div>15</div>
</div>

I was going for something like this, but I get an error saying I have an undefined object.

function loading(){
    var boxes = document.getElementById("puzzlearea").childNodes;
    for(var i=0; i<boxes.length; i++){
        boxes[i].style.height ='100pt';
    };
 };

window.onload = function(){
     loading();
 };

Upvotes: 0

Views: 59

Answers (2)

disfated
disfated

Reputation: 10999

reason:

Some of the childNodes are text nodes (representing spaces between <div>s), which don't have style property, so boxes[i].style resolves to undefined and trying to get height of that undefined causes the error.

solution:

var boxes = document.getElementById("puzzlearea").children;

see:

http://jsfiddle.net/YWz5S/

Upvotes: 2

esswilly
esswilly

Reputation: 239

Make sure that your javascript is placed after <div id="puzzlearea"> in the document or else document.getElementById("puzzlearea") will return null.

Upvotes: 0

Related Questions