Skip to content
CodeKruPro

Switch into a frame by its id

Automation taskMediumAsked in: Accenture, Capgemini, Cognizant, Infosys, TCS, Wipro

"The element is on screen but Selenium says it does not exist. Why?" Often it sits inside an iframe, a page inside the page. Switch into the frame first, then find the element.

Switch to Frame by ID

Switch to Frame by ID

Frames (iframes) are separate HTML documents embedded in a page. To interact with elements inside a frame, you must first switch to it.

driver.switchTo().frame("frameId") switches to a frame by its ID.

On the Frames page, the first frame has id="frame1" and contains an <h1> with text "CodeKru".

Page DOM Structure:

<!-- Main page content -->
<h2>Frames</h2>

<iframe id="frame1" srcdoc="...">
  <!-- Separate document inside frame1: -->
  <body>
    <h1>CodeKru</h1>
  </body>
</iframe>

You must switchTo().frame() before you can access elements inside the iframe.

Task:

  1. Navigate to https://testkru.com/Interactions/Frames
  2. Switch to the frame with ID frame1
  3. Find the h1 element and print its text
  4. Switch back to default content

Expected output:

Frame content: CodeKru