What is the best way to insert an iframe using getElementById?

I am looking to make some changes in the JavaScript code below by removing the image logo.png lines and replacing them with iframe code.

currentRoomId = document.getElementById('roomID').value;

if ( document.getElementById('room_' + currentRoomId + '_bg') ) {
    document.getElementById('login_banner').src = document.getElementById('room_' + currentRoomId + '_bg').value;
}
else if ( document.getElementById('login_banner').src != "http://somedomain.com/header/logo.png" ) {
    document.getElementById('login_banner').src = "http://somedomain.com/header/logo.png";
}

if ( document.getElementById('room_' + currentRoomId + '_bg_link') && document.getElementById('room_' + currentRoomId + '_bg_link').value != 'FREE' ) {
    document.getElementById('login_banner_link').href = document.getElementById('room_' + currentRoomId + '_bg_link').value;
}
else if ( document.getElementById('login_banner_link') ) {

I want to replace this piece of HTML:

<img src="http://somedomain.com/logo.png" id="login_banner" /></a>

with this iframe element:

<iframe class="animation" src="http://somedomain.com/header/index.html" id="login_banner"></iframe>

This change will help the backend determine whether to display the default banner or a client banner.

The JavaScript code needs to be updated accordingly to generate the final HTML output.

Thank you.

Answer №1

If you are looking to achieve a specific task with vanilla javascript, you can utilize the following code snippet to replace an image with a frame:

// create a new iframe element
var frame = document.createElement("iframe");
frame.className = "animation";
frame.id = "login_banner";
frame.src = "http://somedomain.com/header/index.html";

// insert the frame before the image
var img = document.getElementById('login_banner');
img.parentNode.insertBefore(frame, img);

// remove the existing image
img.parentNode.removeChild(img);

If your intention is different, feel free to provide more details for better assistance.


If you wish to incorporate this code within the lastelse if condition in your current code snippet, it should be included as follows:

currentRoomId = document.getElementById('roomID').value;

if ( document.getElementById('room_' + currentRoomId + '_bg') ) {
    document.getElementById('login_banner').src = document.getElementById('room_' + currentRoomId + '_bg').value;
}
else if ( document.getElementById('login_banner').src != "http://somedomain.com/header/logo.png" ) {
    document.getElementById('login_banner').src = "http://somedomain.com/header/logo.png";
}

if ( document.getElementById('room_' + currentRoomId + '_bg_link') && document.getElementById('room_' + currentRoomId + '_bg_link').value != 'FREE' ) {
    document.getElementById('login_banner_link').href = document.getElementById('room_' + currentRoomId + '_bg_link').value;
}
else if ( document.getElementById('login_banner_link') ) {
    // create a new iframe element
    var frame = document.createElement("iframe");
    frame.className = "animation";
    frame.id = "login_banner";
    frame.src = "http://somedomain.com/header/index.html";

    // insert the frame before the image
    var img = document.getElementById('login_banner');
    img.parentNode.insertBefore(frame, img);

    // remove the existing image
    img.parentNode.removeChild(img);
}

If you simply want to understand how to add an iframe to your HTML page, here is the code snippet for reference:

<iframe class="animation" src="http://somedomain.com/header/index.html" id="login_banner" height="400" width="400"></iframe>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering if an input field is read-only or not can be achieved by using Selenium WebDriver along with Java

Currently, I am utilizing selenium webdriver along with Java to create a script. One issue we are encountering is that certain fields become disabled after clicking on a button. We need to determine if these fields are transitioning into readonly mode or ...

Issue with displaying record attribute as a text variable

I'm currently attempting to retrieve the attribute odata.type from a record so that I can adjust my EditForm based on its value. Strangely, when I utilize a constant to achieve this and print it with console.log, it appears as follows: ƒ HWType(_ref ...

Problem: Values are not being posted with AJAX when using $(form).serialize()

I'm encountering an issue with submitting a form using AJAX. I initially tried to pass the data using $("#myForm").serialize(), but for some reason, the receiving page doesn't receive the data. Take a look at my form: <form id="myForm"> ...

Saving JSON Data into my HTML document

Currently, I am in the process of learning about API's at school which means my knowledge of jQuery is quite limited. However, I have a specific task that involves making an API call and using the retrieved information. Recently, I conducted an ajax ...

Trying to filter out repetitive options in an autocomplete box

Using the jQuery autocomplete plugin, I am trying to display 5 unique search results. Initially, I achieved this by limiting the stored procedure to return only 5 results, but now I want to remove duplicates while still showing 5 distinct results. I'm ...

`Integrate Passport Azure AD authentication into your GraphQL Server's Context`

Seeking assistance from experienced individuals to tackle some async JavaScript issues. I am trying to secure a GraphQL server using the Passport library and the passport-azure-ad strategy. The validation of incoming Access Tokens seems to be working fine ...

Learn how to creatively style buttons with dynamic effects using tailwindcss

My Desired Button: I have a Button component that can accept a variant prop. My goal is to have the button's className change dynamically based on the prop passed to it. Instead of using if/else statements for different buttons, I want to use a sing ...

Unraveling and interpreting all incoming requests to my Node.js application

Looking for a simple method to identify and decipher all encoded characters in every URL received by my Node.js application? Is it possible to achieve this using a middleware that can retrieve and decode symbols such as & ? ...

Ramda represents a distinct alternative to traditional vanilla JavaScript

I'm feeling a bit confused about how Ramda really works. I found this code and I'm not entirely sure how it functions. const render = curry( (renderer, value) => is(Function, renderer) && renderer(value) ); I just need to grasp an ...

preventing the propagation of another event

Is it possible to listen for a change event on a checkbox without triggering a click event on its container? <label><input type="checkbox"> Hello world</label> I need the action triggered by the checkbox's change event, but I want ...

Is it possible to add a class to a child element deep within the component hierarchy while using TransitionGroup/CSSTransition in React?

I currently have a setup like this: Parent Component: <TransitionGroup> { items.map((child, index) => { // do something return ( <CSSTransition key={index} nodeRef={items.nodeRef} timeout={1000} classNames={'item ...

Integrating TypeScript into an established project utilizing React, Webpack, and Babel

Currently, I am in the process of integrating Typescript into my existing React, Webpack, and Babel project. I aim to include support for file extensions such as [.js, .ts, .tsx] as part of my gradual transition to Typescript. I have made some progress, b ...

Combine multiple arrays of JSON objects into a single array while ensuring no duplicates

Trying to combine two JSON arrays into one without duplicates based on date. The jQuery extend() function isn't doing the trick, so looking for an alternative solution that avoids nested $.each statements due to potential large dataset size... [ ...

Error: AJAX encountered an unexpected token

An error message has appeared stating: Uncaught SyntaxError: Unexpected token : This error relates to the following line of code: data: userCoupon: $('#couponCode').val(), Here is the script in question: $(function() { $("#signInButton2"). ...

Enhancing User Experience with React-Redux: Implementing Subcategory Visibility based on Main Category Selection

How can I implement action logic to show and hide elements based on user interaction with main categories? Currently, all subcategories are being displayed at once, but I want them to be shown only when a user clicks on the corresponding main category. For ...

Having trouble with dynamic path generation for router-link in Vuejs when using a v-for loop?

//main.js import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import HelloWorld from "./components/HelloWorld.vue"; Vue.use(VueRouter); const router = new VueRouter({ routes: [{ path: "/", component: HelloWorld }] } ...

Having trouble loading data.json file in React.js and jQuery intergration

Having a background in mobile development, I am relatively new to web development so please excuse any amateur questions. Currently, I am working on a react.js project using create-react-app (which utilizes Babel). I am following a tutorial that requires ...

CloudFront for Amazon - Limit MP3 playback to designated website

I've been trying to find a solution for allowing mp3 files in an Amazon S3 bucket paired with Cloudfront to be streamed directly on my site without revealing the source URL of the mp3s. I want to prevent others from sharing or leeching the link by vie ...

Vue.js $scopedSlots do not function with Vue object

In the process of developing a Vue component that will be released once completed, I am wrapping Clusterize.js (note that the vue-clusterize component is only compatible with v1.x). The goal is to efficiently render a large list of items using Vue, particu ...

Updating a JSON property in JavaScript on the fly

I am looking to dynamically replace the content of "placeholder" with {"John": "Dough"} using a function call. This initial method seems to work fine: a = {foo:{bar:{baz:"placeholder"}}}; a.foo.bar.baz = {"John" : "Dough"}; console.log(JSON.stringify(a)) ...