Is it possible to swap a <div> element with the content of another HTML page using the .innerHTML method?

I am currently working on a project that involves loading different webpages into a <div> on my page once specific links are clicked. I came across a thread about using jQuery for this purpose, but I'm not familiar with it. Is there a way to achieve this using only .innerHTML in JavaScript and CSS without needing jQuery?

Replace <div> with another HTML page

Essentially, I want something similar to w3.includeHTML(), where the entire page loads seamlessly within the existing page, not inside a frame.

Here is a link to my project file. The main HTML page is index.html and the linked HTML page is greatwallofchina.html:

https://drive.google.com/file/d/1yAWZIIhBKHjwkiwwNhXUsQEVVQdjTxrM/view?usp=sharing

Answer №1

To display one HTML inside another, you can utilize the object element and employ innerHTML for this purpose. Here are two functions for each link; one will load the first page, and the other will load the second. The alternative choice necessitates uploading your stylesheet. I hope this information is beneficial. The enhancement to this answer involves eliminating the extra scrollbar.

<script type="text/javascript">
function nextPage(){
document.getElementById('pageContent').innerHTML = "<object style=\"overflow:hidden; width: 99.25%; height: 101%\" width=\"100%\" height=\"101%\" data=\"http://localhost/test/page1.php\"></object>" ;
}
function nextPageB(){
document.getElementById('pageContent').innerHTML = "<object style=\"overflow:hidden; width: 99.25%; height: 101%\" width=\"100%\" height=\"101%\"  data=\"http://localhost/test/page2.php\"></object>" ;
}
</script>
</head>
<body style="float:left; overflow:hidden; width: 100%; height: 101%">
<nav>
<h2 class="hidden">Our navigation</h2>
<ul>
<li><a onclick="nextPage();">Home</a></li>
<li><a onclick="nextPageB();">Contact</a></li>
</ul>
</nav>
<div id="pageContent">Hello motto </div>

Answer №2

Try this:

If you're unsure about the format of these "links" and have access to them, there are a couple of ways you can utilize.

Utilize the HTML and any variation of the following Javascripts (JS)

HTML

<iframe id="myFrameID" src="" width="0px" height="0px" style="display:hidden;visibility: hidden"></iframe>
<div id="myPageViewerDIV"></div>

JS with selectors

$('a[href="formatoflinkhere"]').click(function () { 
    $("#myFrameID").attr("src", $("a:focus").attr("href"));
    $("#myFrameID").bind('load', function() { $("#myPageViewerDIV").html($("#myFrameID").contentDocument); });
    return false;
});

JS with any links

$('a').click(function () { 
    $("#myFrameID").attr("src", $("a:focus").attr("href"));
    $("#myFrameID").bind('load', function() { $("#myPageViewerDIV").html($("#myFrameID").contentDocument); });
    return false;
});

JS with any links but ids (the hash symbol)

$('a[href!=#]').click(function () { 
    $("#myFrameID").attr("src", $("a:focus").attr("href"));
    $("#myFrameID").bind('load', function() { $("#myPageViewerDIV").html($("#myFrameID").contentDocument); });
    return false;
});

You or other users can build upon this concept ^^/'

What this accomplishes:

  1. Generates a concealed IFrame
  2. Binds All Links (or similar types) with the onclick event handler (does not allow browsing to the link)
  3. Loads the link into the source
  4. Binds to the onloaded event of the iframe
  5. Copies the root document of the iframe to the chosen dive...

TL;DR

Not tested, should work theoretically.

Answer №3

To display the content on your div, you can follow the instructions provided below

IMPLEMENTING JAVASCRIPT::

<div id="result">
</div>

<script type="text/javascript">
function loadContent() {
document.getElementById("result").innerHTML = '<object type="text/html" data="/path/of/htmlpage.html" ></object>';
}
<script>

USING JQUERY ::

 $(document).ready( function() {
        $("#yourLinkId").on("click", function() {
            $("#YourDiv").load("../pages/PageYouWantToShow.html");
        });
    });

Answer №4


$(document).ready(function() {
    $("#clickButton").on("click", function() {
        $("#contentDiv").load("../pages/DesiredPage.html");
    });
});

Answer №5

function yourFunction(){
    document.getElementById("element").innerHTML='<object type="text/html" data="/statics/health.html"></object>'
}

Answer №6

If you want to load HTML content by clicking a link, just use a simple JavaScript function like this:

$("#divid").load('path of file')

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

Issues arise when implementing Django templates in conjunction with jQuery

Here is an example of a Django template that I am working with: ... <div class="row"> <div class="col-lg-12"> <button type="submit" class="btn btn-primary" id="related"}>KIRK</button> </div> </div> . ...

An unusual type of data is being stored in a MySQL database through Navicat Premium while using Django

Recently, I've encountered an issue while trying to insert data from an HTML form into my database. Strangely, upon submission, the values for "gender" and "website rating" get replaced with "on" instead of the actual input provided through the websit ...

What is the best way to make my input tags move downwards when resizing the screen?

I need help with a grid layout. My goal is to have the input tags (marked in blue) shift below when resizing the browser or viewing on a mobile or tablet device, while keeping the other three tags on the same line. I attempted to position the small box to ...

What is the best way to retrieve the Axios response using Express?

I've recently delved into working with Express and I'm currently struggling with making an Axios request using route parameters, and then updating some local variables based on the response. Here's a snippet of what I've been working on ...

The webpack-bundle-analyzer tool reveals that running webpack -p does not eliminate the development dependency react-dom.development.js

Here is my custom webpack configuration: const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const SO ...

CSS Grid: Dividing items equally based on the number of items present

Currently, I am delving into grid layouts in CSS and experimenting with code to divide a row. Here is the snippet I am playing around with: .grid-sample { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; row-gap: 4rem; padding: 0 5rem ...

What is the best method for comparing two JSON objects in AngularJS?

I am working with two JSON objects. $scope.car1={"Sedan":{"Audi":["A4","A3"]},"Hatchback":{"Maruthi":["Swift"]}}; $scope.car2={"Hatchback":{"Maruthi":["Swift"]},"Sedan":{"Audi":["A3","A4"]}}; I have attempted to compare these two objects using the co ...

Using jQuery to create a Select All Checkbox that toggles a specific class

I have come across similar examples in the past, but I have been unable to make it work as intended. The examples I found only use standard checkboxes. I attempted to customize the checkbox using a sprite sheet by applying a class, but I am struggling to a ...

Finding the latitude and longitude coordinates of a point at a specific distance from another using Node.js or JavaScript

My task involves determining the square area based on a latitude and longitude (x,y) as shown in the provided figure. To accomplish this, I must calculate the coordinates of the remaining three corners by adding 10 kilometers to each side. I will be using ...

Looking for an Angular Material component that displays a list of attributes?

I am trying to create a dynamic list of properties in Angular using Material Design that adjusts for different screen sizes. For example, something similar to this design: https://i.stack.imgur.com/EUsmV.png If the screen size decreases, the labels shou ...

Tips on displaying a message when search results are not found

import React, { useState, useEffect } from 'react' import axios from 'axios' function DataApi({ searchTerm }) { const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useSta ...

Attempting to grasp the concept of implementing an If statement in conjunction with an event

Check out this HTML code snippet <body> <div> <button> Button A </button> <button> Button B </button> <button> Button C </button> </div> </body> This is my att ...

Ionic Troubleshoot: Issue with Reading Property

Encountering an error: A TypeError occurs: Cannot Read Property of "username" of Undefined The HTML code responsible for the error is as follows: <ion-content padding style="text-align: center; margin-top: 35px"> <form (ngSubmit)="logFor ...

How can I ensure the Jquery datepicker functions correctly?

I've been attempting to create a jsp page with some Jquery functionalities. Unfortunately, despite my best efforts, I am unable to make it work. I have downloaded jquery1.7.1 and jquery-ui1.8.17 (non-mini), renamed them to jquery171.js and jquery-ui. ...

Struggling to calculate the total of a property within an array of objects

I'm currently trying to calculate the sum of a specific property within an array object. Although I successfully accomplished this in one component, I am encountering difficulties replicating it in another. The error message being displayed is: this. ...

Step-by-step guide on crafting a harmonious row of a label and a responsive button group

One of my projects involves a form that contains a list of elements. I want this form to be responsive and suitable for all screen sizes. When I initially run the project on a larger screen, everything looks good. However, when I resize the screen to a sma ...

Displaying dates in Meteor Handlebars using `{{ timestamp }}` braces

Looking to shorten the timestamp output in Meteor's Handlebar bracers. How can you convert {{ timestamp }} from Thu Jul 25 2013 19:33:19 GMT-0400 (Eastern Daylight Time) to just Jul 25? Attempted using {{ timestamp.toString('yyyy-MM-dd') } ...

How can you refresh the .replaceWith method in jQuery?

Is there a way to reset the .replaceWith function so that the html, css and javascript elements are restored to their original state? I am looking to have an icon replace the text when the user clicks on "contact", and then have the text return when the u ...

Enhance Your jQuery Skills by Adding Custom Directories to Anchor Links

Can jQuery be used to add a custom folder name in front of all links on a webpage? For example, if the website has these links: <a href="/user/login">Login</a> <a href="/user/register">Register</a> <a href="/user/forum">Foru ...

What are the steps for transmitting an array of data to Parse Cloud Code?

Trying to send an array of contact emails as a parameter in Cloud Code function for Parse, here is how I am doing it: HashMap<String, ArrayList<String>> params = new HashMap<>(); ArrayList<String> array = new ArrayList<>(); a ...