Replacing contents of html page using another html page - javascript

I am trying to avoid header, sidebar info repeating of my html page template.
So, I was thinking to user innerHTML to replace the contents on the fly. However, I do not want to put entire target html on the same page under innerHTML as it will be nightmare to debug or maintain later.
So, is there a way to specify the another page link in the innerHtml and have contents separate?
just as an example
<script type="text/javascript">
function replacePage(page){
var ele = document.getElementById('page-wrapper'); ele.innerHTML = "<div>hey vik</div>";
}
</script>
I'm looking if i can specify the innerHTML value as some .html file name and move the <div>hey vik</div> there.

ok guys i finally used jquery to do this. What I did was instead of loaded content part, i actually moved the static part into a .html file and then loaded it via jquery as
$(function() {
$("#includedContent").load("navbar.html");
};
the place where i need to rander it i added as below
<div id="includedContent"></div>

You can use document.documentElement to select the root element of the document and the store it in a variable:
let content = document.documentElement;
And then use innerHTML to change the page content:
content.innerHTML = "<body><h1>text</h1><body>";

Related

How to access a Javascript file from multiple html files

Say I have 2 html files, index.html, and example.html and they both use script.js. If I were to use a statement like document.createElement("p"); in the script, how would I specify which html file I want to make the paragraph in?
One way to do this is to play with classes/IDs. The JavaScript file will work on whichever DOM is loaded, whether it's a DOM based on your first HTML or the second.
If you were to do this, you could--in theory--have a specific ID on one HTML file and another ID on the other. Your JS file can append the paragraph to the node with that ID, but only if the ID is actually on the DOM.
This is far from ideal though.
If you don't want the element to be created in every HTML file in which the JS file is included, the code should be invoked from the HTML file as appropriate. For example, you would add a <script> block in the HTML file that calls createMyElement, and createMyElement would be a function in the shared JS file.
Where do you intend on injecting the paragraph element? You could give each section a different id and do something along the lines of :
function InjectHtmlElement(bodyId, element, modifyBodyCallBack)
{
let body = ducement.getElementById(bodyId);
if(body == null)
{
return
}
modifyBodyCallBack(body, element);
}
<body id="first"></body>
<body id="second"></body>
This isn't ideal but it'll work.
by appending the node element to an element in the desired file.
var p = document.createElement("p");
document.body.appendChild(p);
to learn more about appendChild

Force browser to reload javascript files

I tried like this
<script type="text/javascript" src="myfile.js"?+Date.now()></script>
In browser it is showing as it is.
I want to add some timestamp to each js files.
i.e.,
<script type="text/javascript" src="myfile.js"?+5671836294></script>
Thanks in advance.
You can't randomly stick JavaScript anywhere you like in HTML.
When you are in the middle of an HTML start tag you can either:
End the tag with >
Write an attribute
JavaScript does not belong there.
If you want to generate an HTML attribute value dynamically when the element is created, then you must create the entire element with JavaScript.
e.g.
<script>
var s = document.createElement("script");
s.src = "myfile.js"?+Date.now();
document.head.appendChild(s);
</script>
… but you'd probably be better of solving this problem by properly configuring your HTTP headers for the script instead.
Refresh the page or rewrite the script tag and append it to the bottom of the body.
But once a page is loaded, it is loaded. You have to redeclare to overwrite.

Script to embed HTML content on page

The scenario: My company wants to have a "content builder" on our customer portal. Using this content builder, the user can check off their requested content (example: about the company, about our products, etc.)
Once the options are selected, I want to provide the user with a script they can place on their website. When run, the parameters in the script will reach out, call our CMS for the appropriate copy, and return the markup.. which should display within their browser.
My question is.. how do I go about doing this? I know how to get the HTML from the CMS, but how do I write the data back into the DOM? Should I just embed an IFRAME? Can I just write out div tags and such onto the host website? Any advice is appreciated, thanks in advance.
You can create markup to insert into the page.
You could add an id attribute to the script tag that gets embedded into the external site and have them place the script tag exactly where you want the content to appear.
<script id="myscripttag" src="..."></script>
then use some code like below to insert the markup before your script tag.
var insertMarkup = function(){
var scripttag = document.getElementById('myscripttag'),
YOURCONTENT = '<h1>hello</h1>',
//parentNode of script tag
p = scripttag.parentNode,
//new element to hold your content
n = document.createElement("div");
n.id = 'mynewdiv';
n.innerHTML = YOURCONTENT;
p.insertBefore(n,scripttag);
};
While a little bit more about the specific content would be helpful, the basic idea will be to use the innerhtml property of the DOM element into which you will be placing content. For example if you have a div with an id of "contentbox" you could write:
var x = htmlstringfromcms();
document.getElementById("contentbox").innerhtml=x;
if you want to append, rather than overwrite the content of the element try
var x = htmlstringformcms();
document.getElementById("contentbox").innerhtml+=x;

How to switch between original DOM and the DOM changed by a Content script?

I'm making a Chrome Extension that changes the DOM of a page. But I would like to give the user an option to switch between the page before the changes and the changed page.
It's a little bit like Google translate where you can change between the orginal language and the translated message.
I could not find anything in my own searches.
I know JavaScript but not JQuery yet.
Thanks for the help.
You could save the entire body in a variable, then start overwriting things. If you want to switch back load up the old body.
You could save all the original DOM content to a variable before running the content script. You can do this by using the following code at the top of your content script:
var originalDOM = document.getElementsByTagName("*");
This saves the entire DOM in an array called originalDOM. The * acts a universal tag, requesting every tag in the document. You can read more about the .getElementsByTagName() API here.
You could try:
var html = document.getElementsByTagName("html")[0];
var page = html.innerHTML;
This will give you everything between the <html> tags.
After the content script is injected, run:
var newPage = html.innerHTML;
Now, whenever you want to switch between the pages, simply run:
html.innerHTML = page; //or newPage
You can read more about the .getElementsByTagName() API here

Am I safe executing this outside "document.ready()" block?

Would I be safe moving this piece of code out from inside the document.ready() block.
var $userInfoNode = $('#userOptions');
CURR_USER_ID = $userInfoNode.attr('data-userId');
CURR_USER_NAME = $userInfoNode.text();
This code is placed in an external js file that is loaded from the head section of html page & selects an html element placed within html body, to extract data from there.
Short answer: No, since the JavaScript file is placed in the header.
The DOM (Document Object Model) needs to contain the <div id="userOptions"> when the code is executed.
Either you place the code after the div, for example right before the closing </body>.
Or you place the code within the $(document).ready() function, which is triggered as soon as the DOM is fully loaded.
out of the document.ready() block.
external js file that is loaded from the head section
selects an html element placed within html body
=> No. You can try it and will find $userInfoNode empty.
Yes.
You also need to ensure that the html elements you are going to refer to appear before your javascript.
in short put this
var $userInfoNode = $('#userOptions');
CURR_USER_ID = $userInfoNode.attr('data-userId');
CURR_USER_NAME = $userInfoNode.text();
at the end of your html page...
If you have to/want to keep it in an external file you can place the script element that references it at the bottom before your closing body tag. It looks a little weird at first but it is valid.

Categories