0

i am trying to pop up a window including a video inside it . but using getElementById doesn't work for multiple videos using the same code. I am trying to use getElementByClass but it doesn't work for me. What am i missing ? Thanks in advance.

working code

    var overlay = document.getElementById('overlay');

    function openModal() {
    overlay.classList.remove("is-hidden");
    }

    function closeModal() {
     overlay.classList.add("is-hidden");
    }    

what i was trying to do (not working):

    var overlay = document.getElementsByClassName('overlay');

my html:

    <a class="buttonPlay" onclick="openModal();" href="#" style="visibility:visible;color:#ffffff;font-size:24px;">Play movie</a>

                <div class="overlay is-hidden" id="overlay">

                    <a href="/" class="cancel">&times;</a>

                    <div class="video-responsive" style="overflow: visible; padding-bottom: 56.25%; position: relative; height: 0; top: 20%; left: 20%;">
                        <iframe src="@videoSrc" width="500" height="281" style=" left: 0; top: 0; height: 60%; width: 60%; position: absolute; " frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
                    </div>
                </div>
user12
  • 197
  • 2
  • 11
  • 3
    Can you show your html? Did you add an overlay class? – James Brierley Aug 21 '15 at 10:11
  • 1
    var overlay = document.getElementsByClassName('overlay'); This will give you the collection not a single object. You have to loop through this collection to apply your changes in all the elements having the "overlay" class. – Naveen Chandra Tiwari Aug 21 '15 at 10:12
  • Unlike `getElementById` which returns single element, `getElementsByClassName` returns an array, You will have to loop through your `overlay` variable to make your code work. :) – AdityaParab Aug 21 '15 at 10:13

1 Answers1

3

.getElementsByClassName returns a node list, I.E. an array-like object containing all DOM elements that match the query passed.

If you want to change properties for the elements returned, you can loop through them:

function openModal() {
    for(var i = 0; i < overlay.length; i++){
        overlay[i].classList.remove("is-hidden");
    }
}

Or, you can target a specific element in the collection:

overlay[0].classList.remove("is-hidden"); // First match

JSFiddle

George
  • 36,413
  • 9
  • 66
  • 103
  • thanks it works pretty fine. but when i am attempting to use dynamically suppose to show only item 2 or only item 1 it doesnt filter instead it all overlaps on top of one after another ! I am using bettercms to create an popup instance. – user12 Aug 21 '15 at 13:33