How can a particular frame be targeted, from a hyperlink, in JavaScript?


HTML frames gives a convenient way to divide a browser window into multiple sections.

Where each section can load a separate HTML document. We can use JavaScript to load the content into a particular frame using the frames property of the window object. The frames property is an array-like object containing all the frames (including iframes) on the current page.

There are many ways in which we can use window.frames[] property to load the content of a document into the frame. Let’s look them one by one −

1. Using Index

To target a specific frame, you can use the frame's index or name. For example, to target the first frame on the page, you can use the following code −

window.frames[0].document.location.href = "http://www.example.com"

2. Using Frame Name

To target a frame with its name the below method can be used. Suppose the name of the frame is “frame_name” −

window.frames["frame_name"].document.location.href = "http://www.example.com";

3. Using getElementById and getElementByName

You can also target the frames using getElementById() or getElementsByName() method and then use the method contentWindow to access the frame window like this −

document.getElementById("frame_id").contentWindow.location.href = "http://www.example.com";
document.getElementsByName("frame_name")[0].contentWindow.location.href = "http://www.example.com";

Example

The following is the complete working code snippet including all these methods −

<!DOCTYPE html>
<html>
<head>
   <title>Target a frame</title>
</head>
<body>
   <button onclick="indexMethod()">Using Index</button>
   <button onclick="nameMethod()">Using Frame Name</button>
   <button onclick="queryMethod()">Using Query Methods</button>
   <iframe src=""
      height="150px"
      width="100%"
      name="frame_name"
      id="frame_id" srcdoc="<html>
         <body style='background-color:#ccc;'>
         <h1>Testing iframe</h1>
         </body>
         </html>">
   </iframe>
   </body>
   <script>
      const indexMethod = () => {
         const child = document.createElement('p');
         child.innerText = 'added inside frame';
         window.frames[0].document.body.appendChild(child);
     };
      const nameMethod = () => {
         const child = document.createElement('p');
         child.innerText = 'added inside frame';
         window.frames["frame_name"].document.body.appendChild(child);
     };
     const queryMethod = () => {
         const child = document.createElement('p');
         child.innerText = 'added inside frame';
         document.getElementById("frame_id").contentWindow.document.body.appendChild(child);
     };
   </script>
</html>

Updated on: 06-Feb-2023

359 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements