Manipulate multiples HTML files with javascript - javascript

Is it possible to manipulate more than one HTML file in the same script?
For example, i have a <div id="div1"> on my index.html, and <div id="div2"> in another HTML file inside of another folder.
What i trying to do is get the content of the second div and replace to my "div1", but the "traditional way" doesnt work:
function replaceDiv(){
let div1 = document.querySelector('#div1')
let div2 = document.querySelector('#div2')
div1.innerHTML = div2
}
I'm new to programming, sorry if this is a dumb/obvious question haha
ps: both files have the link for the same script.
ps²: i know that i can manually write the string with innerHTML, but i wanna know if it's possible to do this

Why this doesn't work
The document object in JavaScript is representative of the currently rendered page's content, it can only exist when the page that loads this script is actively being rendered.
A web browser can only render one HTML file at a time (e.g. either index.html or other.html). Say #div1 is in index.html and #div2 is in other.html; the script can only see that one of these div elements exists since the document is scoped to the current page.
This is the same reason that you can reuse ids across multiple HTML files on the same website with no unexpected behavior.
Alternate Solution
Store this data (InnerHTML/the snippet needs to be shared) in the script itself since that can be requested on each page individually.

Related

Is there a way to intercept items before they are added to the DOM in an HTML file

I don't think what I want is possible but I thought I would ask anyway!
Is there a way to grab stuff in the initial HTML file, modify it and then add it to the DOM before it has rendered?
For example I have an HTML file:
<body>
<div>Something here</div>
</body>
Is there a way I can intercept that <div> before it is added to the DOM as the HTML file is parsed.
I do not want to modify it after it has already been added to the page for clarity.
For another example, if I have an <img src="someimage.jpg"> is there a way to change that src attribute before the image gets added to the DOM so the request is never made.
Happy enough to use inline JS in the <head> (well I assume that is what I would have to do anyway if this is actually possible.)
I know once I have a service worker this all becomes arbitrary but I am working on the assumption of a cold cache and no external files (it is to optimise "above the fold" content primarily).
A cheap and simple way to prevent HTML from rendering is to wrap it in a <template>.
Templates will be parsed during page load like any normal HTML, but put in different documentFragments instead of being rendered, waiting to be manipulated, cloned or inserted anywhere you want when you are ready to render.
HTTP requests will not fire.
<template id="some_tpl">
<img src="someimage.jpg">
</template>
const template = document.getElementById('some_tpl');
const templateContent = template.content;
document.body.appendChild(templateContent);

Constructing full HTML page

How can one load a HTML file and run javascript embedded in it to construct full HTML page programatically in the same way as done by browsers?
Edit 1 - I have an application where I am trying to read some data embedded in an html page of a remote website. However, after fetching this page from remote website, I don't see that data because that data is actually loaded by a javascript embedded in this HTML page after browser loads initial markup. So, I need a way in my application to trigger javascript embedded in the HTML page in order to construct full HTML page.
If you mean that you have an HTML file stored on your computer, the only way that you can compile it is with your browser. Just enter the absolute file path in your browser's url input. If I misunderstood your question, leave a comment and I'll correct my answer.
Question needs more details, but depending on what you want:
If you want to dynamically load different HTML documents, see iFrame
If you want to insert elements to an empty html document:
First, make a blank html document
<!DOCTYPE html>
<script src='main.js'></script>
</html>
Then in main.js do:
var html = document.querySelector('html');
// Append remaining page elements to the html element here.
// (the `head` and `body` elements may have been automatically created)
// You will need createElement and appendChild
createElement
appendChild

Javascript Iframe weekday

the question on the assignment asks to insert a command to write the HTML code
to the webpage where weekday is the text string returned by the weekDay() function.
The iframe should display the daily schedules that are stored in the sunday.htm through saturday.htm file.
The weekDay() function is located in an external .js file that I have already linked to my webpage.
Another thing is there is no weekday.htm file instead there are files sunday.htm through saturday.htm that have the daily schedules to de displayed in the iframe.
I know that I should some link the weekday.htm file to the weekDay() function. This is what I have done so far:
<h2 id="title">Today at the Union</h2>
<p>
<script type="text/javascript">
/*
Dispaly the daily schedule in an inline frame.
Display schedules are stored in the files
sunday.htm through saturday.htm
*/
<iframe src='weekday.htm'>
var weekday = weekDay();
document.write(weekday);
</iframe>
</script>
</p>
Please advice as to how to get this thing working. I am not an expert( I am still learning.) I tried my best (spent several hours breaking my head on this). So any help is much appreciated.
Thank you for your time
Do not put HTML code inside of a <script> tag. Generally only JavaScript code is allowed there.
Also anything inside of an <iframe> tag usually gets ignored by the browser (only displayed when the browser doesn't support iframes). So it doesn't make sense to put important things there.
Instead you should separate those tags. In your case you probably want to place the <iframe> tag previous to the <script> tag so that the iframe already exists when the script runs. Then in the script you need to get a reference to the iframe in order to set its src attribute to the correct url.

javascript will not load unless page is refreshed

I am working on a website that was started off by someone else. That person built the whole thing in one 1000-line html file, and links to different 'pages' just reference other sections in the main html file. So my task is to break the page apart into seperate html pages. Unfortunately, now the seperate pages do not load the javascript unless the page is refreshed.
Is there a standard way to fix this problem without forcing the user to manually refresh the page?
If you break that one big page into several smaller pages, make sure you include the JavaScript (and CSS) in the new pages. The most efficient way to do this is to have the JavaScript in an external JavaScript file, and bring that file into the new pages by putting the script tag inside the new pages' head tags like so:
<head>
<script src="path/to/javascript/app_name.js"></script>
</head>
When the user clicks on a hyperlink to see one of the new pages, when the browser receives the response from the server, it will parse the response and execute the JavaScript.
If I understand your problem correctly, I would wrap whatever "detailsScreen.js" does into a function and call it after you changed the page content.

Load a html page in a div by clicking an image

I have an image and i want, once i click it, that a particular html page is displayed into a specific div. I found several answer yet, but none of them seems to work.
I'm thinking something simple with jquery, like the answer given here: display html file in a div
What's your solution ?
Thanks in advance.
EDIT1
I want to load an internal html page ( not an external page from another webiste ) by clicking an image.
This is the code i used taking example from the answer on the link above.
<script type="text/javascript">$(document).ready(function(){$("mainscreen").load("/home/dontrythisathome/Programmazione/HTML/Progetto-Corso-Inglese/Misc/FILE/HTML/ChiSiamo.html");}</script>
"mainscreen" is the final div when i want to display the html page.
Inside the function .load() there is the path of the html page.
But no html page is displayed into the div.
EDIT2: I found the silly mistake. I use this structure: when the correct position of the elements is . I could remove also the element but i'm using CSS and i'm more comfortable to place elements than using tag options instead. Thanks for all your replies. Tomorrow i'll see if the code with jquery works.
I think your Problem is, that when you load another website using .load().
All the other websites CSS/JavaScript gets loaded and yours gets overwritten.
Could you tell us, what you are trying to accomplish?
Are you loading a html-page from your own website or an external url?
If you dont care for the styles that other website uses, you could do something like this:
.load("example.com/some.html #content");
This loads the url you specifies and just copys the content of the HTML-Element that corresponds to this selector into your target element. (ONLY INLINE-CSS will be applyed that way, you would need to do that styling manually)
EDIT: Thank you for updateing your question.
You are trying to load a file from your filesystem.
Add file:// in front of the path to your .html file.
NOTE: Especially when you are trying to use AJAX you should use a local website and work with relative paths! This makes it much easier to deploy the website afterwards as you do not have to rewrite all your URLs.
Here is jsFiddle
Your html code
<img class="img" src="http://www.lessons4living.com/images/penclchk.gif" width=100 height=100>
<div class="targetDiv"></div>
Your javascript
$(document).ready(function(){
$(".img").click(function(){ //capture the event and ignite your work
loadPage("http://fiddle.jshell.net/"); //call our function
});
});
function loadPage(link){
$.get(link,function(data){ //dont forget cross-browser rules.
$(".targetDiv").append(data) //appended in to your div
})
};
Or you can use .load function with link parametre.
Lets say you have the following HTML code.
<div id="mainscreen">click on the image to load html …</div>
<img id="js-image" src="http://cl.ly/image/0A1P1s3r2M0u/Bildschirmfoto%202014-05-24%20um%2021.59.23.png" />
And some JavaScript code (with jQuery).
var image = document.getElementById('js-image'),
mainscreen = document.getElementById('mainscreen');
$(image).on('click', function() {
$(mainscreen).load("http://fiddle.jshell.net/florianpircher/tmRy9/show/");
});
Demo: http://jsfiddle.net/florianpircher/6wXBu/1/
You can not use $("mainscreen") because that would select <mainscreen> and not #mainscreen. In jQuery, you need a CSS-selector (like $("#mainscreen")).

Categories