What is the best way to update the content of a div on an HTML page by incorporating the content of a div from a different page using JavaScript?

I have a requirement where I need to implement a link in a Table of Contents that, upon clicking, should replace the existing content of one div on a page with the content of another div on a different page. My goal is to accomplish this using only JavaScript.

Below are the code snippets from the two pages:

Original Page (to receive new content)

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>

<script type= "text/javascript">
    function loadContent(targetPage){
        document.getElementById("content").innerHTML = "New text!"; //I am looking for a way to fetch the contents of a div from another HTML file
    }

</script>
</head>

<body>
<div id="link">
    <a href="#"  onClick="loadContent("newContent.html")">Click Me.</a>
    </div>
    <p></p>
<div id="content">
    <p>This is the original content.</p>
</div>


</script>
</body>
</html>

Source Page

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Content Source</title>
</head>

<body>

<div id="newContent">
    <p>New Content:</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ultricies lacus sed turpis tincidunt id aliquet risus feugiat in. Est velit egestas dui id ornare arcu. Ultricies leo integer malesuada nunc vel. Risus sed vulputate odio ut. Senectus et netus et malesuada fames ac turpis egestas.</p>
</div>

</body>
</html>

Answer №1

One method to embed one HTML page within another is by using an iframe. In this case, the content inside the div was replaced with an iframe element that points to the specified HTML page as its source. Additionally, a style was added to ensure the iframe fills the entire page.

<html>
<head>
<meta charset="UTF-8">
<title>Embedded Page Example</title>
<style type="text/css">
.embeddedIframe{
width:100%;
height:100%;
float:left;
border:0px;
overflow:hidden;    
}
</style>
<script type= "text/javascript">
function loadContent(){
document.getElementById("content").innerHTML = "<iframe class=\"embeddedIframe\" src=\"page2.html\" name=\"embeddedFrame\"></iframe>"; 
}
</script>
</head>
<body>
<div id="link"><a href="#"  onClick="loadContent();">Click Here.</a></div>
<div id="content"><p>This is the original content.</p></div>
</body>
</html>

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

difficulty with displaying the following image using jquery

I have referenced this site http://jsfiddle.net/8FMsH/1/ //html $(".rightArrow").on('click',function(){ imageClicked.closest('.images .os').next().find('img').trigger('click'); }); However, the code is not working ...

Browser comparison: Chrome and Firefox - peculiar ID name causing table width difference without CSS. Suspected AdBlocking interference

There seems to be an issue with a table I have in Chrome. Whenever I change the ID name, it either sets the width to zero or doesn't display at all. You can view it here: http://jsfiddle.net/kdubs/W6GTE/ The specific line causing trouble is: <ta ...

Issue with an external library in Angular 2

After generating my Angular 2 library using the yeoman generator and adding it to my main Angular project, I encountered errors when running the app in production mode. The specific errors include: WARNING in ./src/$$_gendir/app/services/main/main.compone ...

Exploring the art of reading and writing to a file with JavaScript and NodeJS

I am currently working on creating a function that will scan a file and remove all content below a specific line before adding new lines to the file. So far, I have successfully read the file and identified the target line: function analyze() { lineRe ...

Utilizing database information for interactive objects in Three.js: A step-by-step guide

I need to display specific text data for each object based on database entries in my project. However, despite creating a cube for each entry in the database, I'm encountering issues with undefined data. It seems like my code should work, but it' ...

Ways to clearly establish the concept of "a"

module.exports.getData = function (id) { const userData = require("./data/Users.json"); if (userData.find(user => user.uid === id)) { return user.name; } else return "User"; } I'm trying to display the name of a user, but the consol ...

Generating a dynamic table using Angular

My goal is to populate a table dynamically using the code below: teams.component.ts import { Component, OnInit } from '@angular/core'; import { first } from 'rxjs/operators'; import { TeamService } from 'src/app/services/team.ser ...

Unable to view any output in the console while attempting to troubleshoot a login functionality

My current setup involves using Node.js with Express and Pug templates. I have encountered an issue with a login function that is not functioning as expected. In order to troubleshoot the problem, I attempted to log the credentials (email and password) to ...

What is causing the additional space at the bottom?

Why does my centered black border triangle have an extra bottom margin causing a scroll bar to appear? * { margin: 0; padding: 0; box-sizing: border-box; } body { height: 100vh; width: 100%; background: blue; } .canvas { border: 10px s ...

Using Selenium, effortlessly upload JPEG images through the Selenium webdriver

Sample HTML Code: <form id="frmUploadVisualAsset" enctype="multipart/form-data" method="Post" action="uploadVisualAsset" novalidate="novalidate"> <input id="slideIdForAsset" type="hidden" name="slideIdForAsset"> <input id="course ...

What is the process for transferring information from a Ruby controller to an application JavaScript using AJAX?

When clicking a button, an AJAX call is made in my application.js file. It sends 3 data points to the events_controller#check action: //application.js $(document).on('click', "#check-button", function(){ ... $.ajax({ ...

The term "this" in the global scope versus within a function in the Node.js environment

console.log(this) // {} function abc(){ console.log(this) } abc() // global The concept of this can vary between the global space and inside a function in Node.js. console.log(this === module.exports) // true function abc(){ ...

When a page loads, automatically refreshing a row in MySQL

I've been searching around, but haven't found a solution to my basic issue. I need help with creating a system where a user can only view a page once per day. Currently, clicking a button updates the MySQL Row, but users can bypass this restricti ...

Different option for positioning elements in CSS besides using the float

I am currently working on developing a new application that involves serializing the topbar and sidebar and surrounding them with a form tag, while displaying the sidebar and results side by side. My initial attempt involved using flex layout, but I have ...

Failure to trigger AJAX error function when database match is not located

UPDATED: Having some issues with my code entry box when a match is not found in the database. Below are the results for both a good and bad match. Check out my code snippet: function checkDiscountCode() { var discount; if ($('#dbReturnString') ...

Sending Multiple Sets of Data with Jquery Ajax.Post: A Step-by-Step Guide

I am currently working with asp.net mvc and I have a requirement to send two sets of database information from jQuery to my Mvc view. Here is an example of how my view looks like: public ActionResult MyView(Product one, Product two) { } Now, my question ...

Using conditional CSS in React/Next.js

While using Next.js, I have implemented conditional rendering on components successfully. However, I am facing an issue where the CSS styles differ between different components. Code 1: import React from "react"; import Profile from "../../ ...

Is it possible to edit YouTube images or embed YouTube iframes without needing an account?

Recently, I developed a YouTube video sharing system but have encountered some uncertainties. My approach involves extracting the YouTube ID and embedding it in an iframe (I wonder if YouTube permits this). To enhance the visual appeal of the posts, especi ...

Performing mathematical calculations with numerical values

This piece of code was created as a component of a calculator project for learning purposes. It functions correctly for the most part. However, I noticed that the addition operation seems to concatenate the two numbers together instead of actually adding ...

What is the best way to ensure items are aligned to the top of the navbar as a picture is enlarged?

I have searched through various similar questions, but none of them have provided a solution to my specific issue. I have attempted multiple suggestions, but none have been successful. (I am working with bootstrap4) Here is the html code I am using: < ...