'Displaying a certain view from a text/view script
I have as a requirement of a project to load the HTML code inside this text/view script that should be displayed the first time the user loads the page. How do I make the browser read the code inside the first script? And how for example I can do the same thing only for the second script?
<html>
<head>
<script type = "text/view" id ="welcomeview">
Hello World!
</script>
<script type = "text/view" id ="profileview">
<h4>Happy Birthday!!<h4>
</script>
</head>
<!-- obviously not working -->
<body onload="welcomeview">
</body>
</html>
Solution 1:[1]
Here is an HTML5 serialized as XML way (strict) example code for you to learn from. You will want to look up different parts to learn from and there are many different ways to do the same thing.
You can modify the code as much as you want to figure out when you remove X or Y how it will break the page. Again, this is all very strict code which is much better for learning and just using in general because it will be much more verbose of when do you something wrong.
Save this file using a proper editor such as Notepad++ (Windows only, not sure about Mac / Linux) as example.xhtml, do not use the regular html extension. Good luck!
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<script type="application/javascript">
//<![CDATA[
//This is a JavaScript comment, not the same as an HTML comment.
//The CDATA thing helps the browser avoid code being interpreted as HTML (in short).
//There is no such thing as "text/javascript" or "text/view", use "application/javascript".
//Define a function that will be called:
function test_function()
{
var example_string = '<p xmlns="http://www.w3.org/1999/xhtml">Happy birthday! This is an example of a string that LOOKS like but is not HTML.</p>';
//You MUST have the XML Namespace (xmlns) on the ROOT most element and can not have multiple root elements.
var xml = new DOMParser().parseFromString(example_string,'application/xml');
//You have to import a string next:
var xml = document.importNode(new DOMParser().parseFromString(example_string,'application/xml').childNodes[0],true);
//Now add the element to the DOM (HTML):
document.getElementsByTagName('main')[0].appendChild(xml);
}
//Events should always be at the END of your (JavaScript) code:
window.onload = function(event)
{
//Call one or more functions when the page loads:
test_function();
}
//]]>
</script>
</head>
<body>
<main></main>
<!-- This is an HTML comment, the syntax is different from JavaScript comments. -->
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John |
