Duncan Palmer
Duncan Palmer

Reputation: 2913

Change multiple divs of same id to different heights

So I have multiple divs with the same id 'stick'. I want to iterate through all these elements and give each a random height. here is what I tried:

    <script type="text/javascript">
        for(var i = 0; i < 47; i++) {
            var rand = 200;
            document.getElementsById('stick')[i].style.height= rand+'px';  
        }
    </script>

This code doesn't work sadly. Am I missing something?

Thanks.

Upvotes: 0

Views: 5182

Answers (3)

Kovge
Kovge

Reputation: 2019

You should not add same id for more than one element. Use class names. And document.getElemetsById is not a defined function, only document.getElementById (without "s") that should return one element.

HTML:

    <div class="stick"> </div>
    <div class="stick"> </div>

JS:

<script type="text/javascript">
    var divs = document.getElementsByClassName('stick');
    for(var i = 0; i < divs.length; i++) {
        var rand = 200 * Math.random();
        divs[i].style.height= rand+'px';  
    }
</script>

This may works. But I recommend to use jQuery framework, for JavaScript coding, because these lines become a simpler code in jQuery:

<script type="text/javascript">
     $('.stick').each(function(){            //iterates all elements having stick class
         $(this).height(200 * Math.random());       //inside the callback the 'this' is the current html element. etc ...
     });
</script>

jQuery homepage: http://jquery.com/

Fast including to your website, just import the jQuery from CDN url, inside the head:

   <head>
       ...
       <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
   </head>

Upvotes: 5

Amy
Amy

Reputation: 7466

You can't have multiple elements with the same id. id must be unique. You need to use class and retrieve your elements using class name. You could use jquery to assist you: var elements = $('.stick')

Upvotes: 0

christopher
christopher

Reputation: 27356

ID's should be completely unique within the document. Change your ID's to unique values, and you can reference them individually. If you wish to act on a collection of elements, use the class tag to link them together. To read up on CSS Classes you can look at this documentation. This will help you understand the purpose of classes in HTML and CSS.

Your problem

getElementsByID() doesn't work. getElementByID() is the correct syntax.

So

document.getElementsById('stick')[i].style.height= rand+'px';  

Will become

document.getElementById('stick')[i].style.height= rand+'px';  

Upvotes: 0

Related Questions