Javascript changing innerHTML to a different pages content not working [duplicate] - javascript

This question already has answers here:
Replace innerhtml with external page
(2 answers)
Closed 7 years ago.
EDIT SOLVED:
Below works great. The suggested link marking this a duplicate does not solve the problem.
changeDrinks.innerHTML = '< object type="text/html" data="drinks.html" > </object > ";
What is wrong with my javascript below?
JS :
var changeDrinks = document.querySelector("#menuDropWine");
changeDrinks.innerHTML = 'drinks.html';
I wanted this to change the content of a div to drinks.html webpage. The div's content that is being changed looks like this...
<div id="menuDropWine" class="divBtn">
I've read a couple questions on here already about changing the content of a div. Some used ajax, others used jQuery, but I feel I should be able to just use innerHTML equals a link. Currently this is just changing my div's content to the literal text output of 'drinks.html'. I hope I'm just missing an a href reference or something, as I feel this solution should be simple. The only real reason I want to put this into my website is so it cleans the looks of my index.html to not have so much text content, by storing the text content in different links that just load on a click.
Thanks for your time.

You are misunderstanding the function of innerHTML; it accepts a string of HTML, creates the required DOM structure and injects it into the the target element. The easiest way to achieve what you want is with an iframe, setting its src property to 'drinks.html'.
<iframe src="drinks.html" frameborder="0">Your browser doesn't support iframes</iframe>
Assuming that drinks.html is a full HTML document (has an <html>, <head> and <body> tag), this is really the best route. If drinks.html is a partial HTML document then you could look into using AJAX. I would suggest using jQuery and then you could easily do something like:
$('#menuDropWine').load('drinks.html');

The short answer to your question is that the element will be filled with the text drinks.html, which is not incorrect, but obviously not what you had in mind.
JavaScript is not psychic, so it doesn’t know whether you want to change the content or load from an external document, so this behaviour is perfectly natural.
If you want a simple solution, use an iframe, whose src attribute can be set in JavaScript as follows:
var changeDrinks = document.getElementById("menuDropWine");
changeDrinks.src = 'drinks.html';
BTW note that if you know you are using an id, it is more efficient to use document.getElementById.
If you really want to use innerHTML, as the others have commented, you will have to use Ajax. A simple example, without jQuery, follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<script type="text/javascript">
window.onload=init;
function init() {
var test=document.getElementById('test');
var url='test.html';
load(test,url);
}
function load(element,url) {
var xhr=new XMLHttpRequest();
xhr.open('get', url, true);
xhr.send(null);
xhr.onreadystatechange=function() {
if (this.readyState==4) {
element.innerHTML=this.responseText;
}
}
}
</script>
</head>
<body>
<h1>Test</h1>
<div id="test">Hello</div>
</body>
</html>
Here, test.html is expected to have your new content.

Related

Localizing html content in vue

So I have been using v-html tag to render the html in my vue pages.
But I encountered a string which was a proper html file and it contained text kind of like this:
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
....
<style>
</style>
</head>
<body style="....">
</body>
</html>
The problem is, I have the v-html on a div, but this code starts affecting the whole page and adds its styling to the whole page and not only to that specific div.
I tried adding "scope" to the style tags but it did not work. Maybe because there's also a style inline tag on body?
I need to find a way to make the html affect only on the div it is on, and not the whole page.
Your best bet would probably be to have a better control over the HTML added using v-html. I would suggest to parse it before and keep only the <body> tag. You could do it using a regex, but it would be easier using a dom parser lib. Example with DomParser:
const DomParser = require("dom-parser");
const parser = new DomParser();
export default {
// ...
computed: {
html() {
const rawHtml = "<html><body><div>test</div></body></html>"; // This data should come from your server
const dom = parser.parseFromString(rawHtml);
return dom.getElementsByTagName("body")[0].innerHTML;
}
}
}
Please note that it is an oversimplified solution as it does not handle the case where there is no <body> tag.
First, you should be very careful when using external HTML with v-html as it can make your site vulnerable to various sorts of attacks (see Vue docs).
Now if you trust the HTML source, other problem is how to embed it without affecting your own side. There is special element for this case, <iframe> - it is not without risk and you should definitely read a bit on how to make it safe but it should solve your problem because is "sandbox" external HMTL so it does not affect your site.
https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies

How or can I use JavaScript to append a div tag after the html or body tags?

For a very specific reason I would like to know if you can add a tag either after the body or html tags.
<!DOCTYPE html>
<html>
<body>
</body>
<!-- Can I add a tag here? -->
</html>
<!-- Can I add a tag here? -->
I have noticed this is what the Skype plugin for Chrome does, and would like to know how they did it. I have attached a screenshot of proof.
You can append some element after the body element as such:
var e = document.createElement('a');
document.body.parentNode.appendChild(e);
Attempting to insert an element which is a sibling of the html element results in the following error:
There are several ways to do it, KPthunder's sample springing to mind. You can also just rewrite the content of the entire document and reload it. Ugly, and brutal, but it works.
Note, however, that browsers are not required to honor the element. As mentioned, it's noncompliant, and therefore not guaranteed to work across all browsers. It'll likely work in IE. But that's IE. And IE supports everything. </eyeroll>
I've actually encountered elements that appeared both before and after the HTML element itself, and it wasn't intentional (cough). Likely, this is the case here. My advice to you is, don't try to repeat it.
Sorry for jQuery but, for example
$( "<p>Test</p>" ).insertAfter( "body" );

How to run <script src= > tag from javascript [duplicate]

This question already has an answer here:
Is it possible to use JavaScript inside handlebars.js template
(1 answer)
Closed 9 years ago.
I am having some difficulties implementing Paypal buttons with backbone.js
The problem is that the button is implemented in a script tag:
<script src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"></script>
which i cant run from Handlebars.js because the </script> tag is closing the handlebars <script>
I cant use eval(), or i don't understand how i am supposed to do that with the .
So there you have it. i am kind of stuck. I am out of ideas on how to implement this button with backbone.js the last resort is to ask the server to produce html pages with the script in them and then load them to the page.
i am just refusing to believe that JavaScript has no way to take care of this.
Please help.
This question relates to another question i asked in this subject.
Is it possible to use JavaScript inside handlebars.js template
One option would be to create the equivalent DOMElement in JavaScript and append it to the DOM, eg:
// Start by creating an empty `<script />` tag element
var scriptTag = document.createElement("script");
// You can now start adding attributes to the element:
scriptTag.setAttribute("data-button", "buynow");
// Set the src attribute, note it won't start loading yet.
scriptTag.src = "paypal-button.min.js?merchant=YOUR_MERCHANT_ID";
// In order for it to become part of the page, you need to attach it
// to the DOM, to keep things clean, we will append it to the page's
// <head /> tag.
document.head.appendChild(scriptTag);

create link in javascript function with --- innerHTML = "...<a href='http://...'>HttpLink</a>..."

I'm learning to write with html, but I have one problem I cannot understand.
The following code works in other browsers but not in IE9. I know it has something to do with innerHTML but I could not understand the answers I found for this.
<html> <head> <script type="text/javascript">
function hw_function1() {
var img11=document.createElement("a");
img11.innerHTML = "<html> <body> <a href='http://google.de'>Google</a> </body></html>";
document.body.appendChild( img11 );
}
</script>
<body>
<a href="#" onclick="javascript:hw_function1()";>Test</a>
</body> </html>
What should I change WITHOUT changing the structure (only the innerHTMl-part if possible)?
Since you're creating an a element, you simply assign the href to the element via the .href property.
You can set its text content with .innerHTML as a convenience, though it's not really a "pure" approach.
var img11=document.createElement("a");
img11.href='http://google.de';
img11.innerHTML = 'Google';
document.body.appendChild( img11 );
Another way to set the text content would be like this...
img11.appendChild(document.createTextNode("Google"));
You code is creating another HTML page inside the original. That is wrong and invalid. It's because some browsers are forgiving and correcting things that your code even works.
If you're creating a hyperlink element, you should be adding text or an image or other inline elements inside it using innerHTML.
You should change its attribute to set the href with img11.href='http://xyz.com';

A bookmarklet-friendly Javascript that grabs source?

So,
I'm trying to build a simple bookmarklet that does a whole bunch of stuff based upon the source code (Which, itself, contains javascript.
Essentially, it's taking a number of bits of data from source which it grabs and and finds using regex queries and then manipulates.
I've got everything beyond the grabbing the source code... I just need some help figuring out the source bit.
So, what do I need to do to take the source code of the page I'm currently
document.documentElement.innerHTML will get you everything except the <html> tag itself and the <doctype>. But, this may not be the actual source code, as the html may have changed by some script. It may be better to get the source code via Ajax:
var xhr = new XMLHttpRequest();
xhr.open("GET", location.href, false);
xhr.send();
var source = xhr.responseText;
Once you get the object (with something like document.getElementById()), you can try using .innerHTML
For example
<html>
<head>
<title>Demo</title>
</head>
<body>
<div id="box">I want the code for this <span>html</span></div>
</body>
</html>
The javascript would run something like this
var data=document.getElementById('box').innerHTML;
Here's a demo in JSFiddle:
http://jsfiddle.net/LW2VH/

Categories