Access DOM of an imported local HTML file - javascript

I'm working on a project in which I would like to import a locally stored HTML template using JavaScript.
This template will be dynamically filled with datas that I get by accessing a website REST API.
This is an example of what I want to do :
index.html :
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
</head>
<body>
<div id="loaded-content">
<!-- Here will be displayed the template -->
</div>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
template.html:
<div id="data">
<h1 id="data-name">value</h1>
<p id="first-attribute">value</p>
<p id="first-attribute">value</p>
<p id="first-attribute">value</p>
</div>
datas.json:
{
"datas":
[
{
"name": "value",
"first-attribute": "value",
"second-attribute": "value",
"third-attribute": "value"
},
{
"name": "value",
"first-attribute": "value",
"second-attribute": "value",
"third-attribute": "value"
}
]
}
For each object contained in datas, I want to display the template again.
Currently, I load the template using XMLHttpRequest object. I can display the content of my template but I can't access to the template's DOM to change the value of its elements.
Which method should I use to correctly load my HTML file ?
I'm looking for something in pure Javascript (no jQuery or something).
Thank you for your help =)

Your immediate problem is that your template as it currently stands will result in multiple elements with the same ID, which isn't allowed.
If you have control of the template, change it to be a more traditional template style where vars are bracketed off rather than relying on HTML IDs. So I'd change your template to be:
<div>
<h1>{{name}}</h1>
<p>{{first-attribute}}</p>
<p>{{second-attribute}}</p>
<p>{{third-attribute}}</p>
</div>
This way we can run string replacements via REGEX rather than outputting then interrogating the items by IDs.
Let's say #content is the container element for the templates, data stores your parsed JSON data and template stores the unparsed template string:
var
cntr = document.querySelector('#content'),
html;
//iterate over data items
data.datas.forEach(function(obj) {
//grab all var references i.e. {{foo}} and replace them with actual values, if exist
html = template.replace(/\{\{[^\}]+\}\}/g, function(match) {
var var_name = match.replace(/^\{\{|\}\}$/g, '');
return obj[var_name] || '??';
});
//append the readied HTML to the content container
cntr.innerHTML += html;
});

This is an example. You can use a JSON parser to get the data in the format you need. So here is what you do: create a dummy <div> DOM element to push later, use replace function to replace val with the value of the data variable. Then finally append this to the HTML's div element. If you got the data using an XMLHttpRequest, pass on the data to template. Then replace the placeholders value with the data from parsing JSON. And use replace method to do so. It should work fine.
var template = document.createElement("div");
var data = "Hello world";
template.innerHTML = "<h1>val</h1>";
template.innerHTML = template.innerHTML.replace("val", data);
document.getElementById("myDiv").appendChild(template);
<div id="myDiv">
</div>

Related

How to convert string into html format using ejs in javascript

The scenario is the user will enter the text in HTML format (e.g. <\/b>Testing<\/b>) then the inserted text will get saved into the database(HTML code as a string (e.g. <\b>Testing<\/b>).
I want the string fetched back from the database to be displayed as HTML text (e.g. Testing).
I followed the below snippet but didn't get anything as output.
Note: <%= cData.description %> worked fine when executed simply but displayed HTML code as plain text.
test.js (route file):
var testid = 234123;
b.find(testid, function(data) {
b.otherdet(testid, function(cdata){
res.render('blogdesc',{
Data: data,
cdata: cdata
});
});
});
test.ejs file:
<p class="" id="descid"></p>
<script>
var $log = $( "#descid" );
html = $.parseHTML('<%= cData.description %>'); //description is column in database
$log.append( html );
</script>
https://stackoverflow.com/a/8125053/20394 shows how to emit HTML as-is in EJS, but please make sure that you sanitize that content to avoid XSS.
I've found, where did it go wrong. I was using:
html = $.parseHTML('<%=blogData.description%>');
while the actual syntax should be this:
html = $.parseHTML('<%-blogData.description%>');

javascript array length not accessible in web page

I have a javascript array in an external file:
<script src="assets/players.js"></script>
contents of above array:
window.players = [
"Addison, Jackson",
"Agron, Dmitry",
"Zuccarino, John"
]
I have tried to return the number of records to no avail:
<h3>Sample data file with <script>window.players.length;</script> names:</h3>
What am I doing wrong..?
If you want to write out the length, than you would need to use document.write
<h3>Sample data file with <script>document.write(window.players.length)</script> names:</h3>
Or you could use DOM methods.
<h3>Sample data file with <span id="count"></span> names:</h3>
<script>
document.querySelector("#count").innerHTML = window.players.length;
</script>
Javascript is not a "pre-processed" language, like PHP. Change your code to:
<h3>Sample data file with <span id="output"></span> names:</h3>
<script>document.getElementById("output").innerHTML = window.players.length;</script>
You cannot use template-style coding on the client side. Instead, you need to create any element that you can reference from the script and then manipulate its contents, e.g.
<h3 id="num"></h3>
<script>
document.getElementById("num").innerHTML = "Sample data file with " + window.players.length +" names"
</script>

The html code coming from XML(converted into Json) is giving an object while I need to fetch just the data

XML:
<testText>
<div>
<h1>A heading</h1>
<p>Enter text here</p>
</div>
</testText>
I have to get the data from the XML that is inside the testText tag and display on the screen, however as I am converting the XML into json, the <div> tags are also considered as part of the XML and are getting converted into object. I have tried $sce, ngSanitize, data-bind-html.
JS :
var data= xmlToJs.xml("myXml.xml");
data.then(function(response){
$scope.textData= response.data.testText;
});
I tried this(and several other approaches listed) but did not work:
$scope,trustAsHtml =function(text){
return $sce.trustAsHTML(text);
};
Instead of getting the div tags executed I get this on the screen :
{"div":{"h1":"A heading","p":"enter text here"}}
The data inside <testText> could be anything and we have no control over it.

how to retrieve data from Json file and displaying it in HTML dropdown...?

Hi i have developed simple Html Page using AngularJS which displays Manufacturer Name in drop down on user selection correspondent Manufacturer Id will get displayed in the below text box.
I have used ng-repeat directive to display manufacturer names in HTML Dropdown and ng-model directive to display selected manufacturer Id.
here is my HTML CODE
<!DOCTYPE html>
<html ng-app="jsonapp">
<head>
<script src="angular.min.js"></script>
<title></title>
</head>
<body>
<div ng-controller='JsonController'>
<span>Please select a Manufacturer:</span>
<li ng-model="Manufacturers" ng-repeat="Manufnames in Manufacturers" style="width:350px;">
{{Manufnames.ManufacturerName}}
</li>
// here i wanted to Display Drop Down which will display Manufacturer Names
<input type="text" /> //here i wanted to display correspondent Manufacturer ID
</div>
<script>
var app = angular.module('jsonapp', []);
app.controller('JsonController', function ($scope, $http) {
$http.get('Pipes.json')
.success(function (response) { $scope.Manufacturers = response.Pipesmanuf; });
});
</script>
// since i have stored both Json and HTML on Same Folder i am directly passing json filename to http.get() funtion to retrive data
</body>
</html>
// I have stored both HTML File and Json File in same folder My Json file contains following data:
{
"Pipesmanuf": [
{
"ManufacturerId": 1,
"ManufacturerName": "Avonplast",
"Products": "PIPES",
"ManufacturerLogo": "C:\Users\Suprith\Desktop\Manufacturerlogos\Pipes\avonplast.jpg"
},
{
"ManufacturerId": 2,
"ManufacturerName": "BEC",
"Products": "PIPES",
"ManufacturerLogo": "C:\Users\Suprith\Desktop\Manufacturerlogos\Pipes\BEC.png"
}
]
}
I am New to Angular JS please suggets me how to Load data from JSON File and displaying it using HTML DropDowns or HTML List
Firstly, your JSON is invalid due to the directory paths. Backslashes \ are escape characters. This causes the parse to fail. So simply change your JSON to
{
"Pipesmanuf":[
{
"ManufacturerId":1,
"ManufacturerName":"Avonplast",
"Products":"PIPES",
"ManufacturerLogo":"C:\\Users\\Suprith\\Desktop\\Manufacturerlogos\\Pipes\\avonplast.jpg"
},
{
"ManufacturerId":2,
"ManufacturerName":"BEC",
"Products":"PIPES",
"ManufacturerLogo":"C:\\Users\\Suprith\\Desktop\\Manufacturerlogos\\Pipes\\BEC.png"
}
]
}
This way you are escaping the escape character.
Beyond that, getting the list into a drop down is almost exactly like your list loop:
<select>
<option ng-repeat="Manufnames in Manufacturers">{{Manufnames.ManufacturerName}}</option>
</select>
Plunker: http://plnkr.co/edit/LXvFNZBVzCIZot96JhgP?p=preview
You should take a look at the official tutorial : https://docs.angularjs.org/tutorial/step_01 .
They do something similar specially the step 11.
Basically, if you want something nice and reusable, you should use a service to request the data in your file. Then inject this service in your controller and get the data then display it in the view. With the tutorial, I think you can handle it. Good look!

Can a JavaScript variable be used in plain HTML?

What I mean is, can a variable/array declared and initialized be used in HTML, outside the <script>-tags? Fx.
<script type="text/javascript">
var foo = array('placeholder1', 'placeholder2');
</script>
<body>
<p><!--access the variable here-->foo[0]</p>
</body>
How do you access the variable/array in this case? like this:
<p><script type="text/javascript">document.print(foo[0])</script></p>
??
Two ways to do this. This is the better one:
<script type="text/javascript">
// make sure to do this onLoad, for example jQuery's $()
var foo = array('placeholder1', 'placeholder2');
document.getElementById("fooHolder").innerHTML = foo.toString();
</script>
...
<p id="fooHolder"></p>
Or you could do it this way (which, as Marcel points out, doesn't work in XHTML and really shouldn't be used anyway):
<p><script type="text/javascript">document.write(foo)</script></p>
You can do something like this:
<script>
var str = 'hello there';
document.getElementById('para').innerHTML = str;
</script>
where an element has the specified id:
<p id="para"></p>
you simply cannot access javascript variable outside of the script tag, it is because,
Html does not recognise any variable it just renders the supported HTML elements
variables are used to store the temporary variables, that is for dynamic data, if you want something more dynamic then you can use PHP for that.
Unnecessarily verbose, but using standard DOM methods.
<script>
window.onload = function(){
// you do not need to initialize like this, but I like to
var bar1 = new String('placeholder1');
var bar2 = new String('placeholder2');
var foo = new Array();
// populate the Array with our Strings
foo.push(bar1);
foo.push(bar2);
// create an array containing all the p tags on the page
// (which is this case is only one, would be better to assign an id)
pArray = document.getElementsByTagName('p');
// create a text node in the document, this is the proper DOM method
bar1TextNode = document.createTextNode(foo[0].toString());
// append our new text node to the element in question
pArray[0].appendChild(bar1TextNode);
};
</script>
<body>
<p></p>
</body>
That's the only direct way you'll access it elsewhere in your page. By opening another script tag and printing it.
You can also use methods such as innerHTML to put the value somewhere.
I don't think you can access the javascript from html but you can set the innerhtml of a dom object through javascript so you may want to go the other way around. First google search I found so I cant promise its good but it has a quick sample.
http://www.tizag.com/javascriptT/javascript-innerHTML.php
You can even you AngularJS expression.
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.framework= "AngularJS";
});
</script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>I want to use variables directly in HTML using: {{ framework }}</p>
</div>
</body>
</html>
The above code will print out "I want to use variables directly in HTML using: AngularJS".You can use braces to write AngularJS expression. For example: {{ expression }}.

Categories

Resources