get iframe inside div with javascript

17,831

Solution 1

To get a div by class name:

var allDivs = document.getElementsByClassName("calendar");

Assuming there's only one

var calendarDiv = document.getElementsByClassName("calendar")[0];

Get the iFrame inside:

var iFrame = calendarDiv.getElementsByTagName("iframe")[0];

set an attribute:

iFrame.setAttribute("frameborder", "0"); 

Or, since getElementsByClassName isn't supported in old versions of IE, consider setting the id on the iFrame and simply doing:

document.getElementById("iFrameId").setAttribute("frameborder", "0"); 

Solution 2

First of all, you need to give your iframe id.

After that, you can get your iframe with the function document.getElementById(""), and than to change it's property.

For example:

<html>
<body>
    <div class="calendar">
        <iframe id="myIframe"></iframe>
    </div>
    <script type="text/javascript">
        document.getElementById("myIframe").frameborder = 1;
    </script>
</body>
</html>
Share:
17,831
Rod
Author by

Rod

Single Best Excel Tip

Updated on June 09, 2022

Comments

  • Rod
    Rod almost 2 years

    Is there a way to do the following in JavaScript?

    1. get a div by a class name,
    2. get the iframe inside the div
    3. and add an attribute (frameborder = 0)

    <html>
        <body>
            <div class="calendar">
                <iframe></iframe>
            </div>
        </body>
    </html>
    
  • Andreas Köberle
    Andreas Köberle over 12 years
    Note that document.getElementsByClassName isn't supported in ie8 and lower: caniuse.com/#search=getElementsByClassName
  • Ayman Safadi
    Ayman Safadi over 12 years
    NOTE: document.getElementsByClassname() doesn't work in IE under version 9. Check out alternatives and how to use them gracefully.
  • Adam Rackis
    Adam Rackis over 12 years
    @AymanSafadi - thank you - I edited to notify OP of that. I hate IE.