Home > front end >  How to change content of a html file (like changing images) by clicking on a element of another html
How to change content of a html file (like changing images) by clicking on a element of another html

Time:05-05

I am working on a project, and i want to know if there's any way to change content of a html file like images, text, etc. with javascript (without any framework) by clicking on elements of another html file.

CodePudding user response:

In general the browser will prevent you from editing the content of any file on your hard drive, or any page served from another domain/base url. However, if both files are in the same project as shown below, you can make temporary edits to one file from the other;

/http
|-index.html
|-template.html
|-hello.png

index.html can contain a <script> tag with the following

// first we open a popup showing the other page
let window_template = open("template.html","_blank")

// now we can do whatever we want in the popup window from the original index.html:
let new_img = window_template.document.createElement("img")
new_img.src = "hello.png"
window_template.document.body.appendChild(new_img)

This does not (and cannot) save any changes to "template.html".

To actually make changes to files, you need to run your own server. Then index.html can send a request to the server, and the server will have the ability to make edits on behalf of your browser-based app. Check out Node.js and the Express server library... I found it approachable enough as server frameworks go.

  • Related