Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting data in html with javascript

Using server side scripting it's as easy as pie to inject data in HTML like this (ASP.NET):

//Assuming theTime is a variable
<h1>the time is, @theTime</h1>

But in JavaScript one basically needs to:

Create an element:

<h1></h1>

Give it an ID:

<h1 id="whatever"></h1>

Create a script tag:

<script></script>

Locate the element by it's ID:

document.getElementById("whatever")

Then use innerHTML to modify it's content:

document.getElementById("whatever").innerHTML = "Hi, " + TheTIme;

Final code:

<h1 id="whatever"></h1>
<script>
    document.getElementById("whatever").innerHTML = "Hi, " + TheTime;
</script>

Is it possible to inject values/data in JavaScript as one would do in ASP.NET / PHP?

EDIT: The variable is a JS variable and getting it from the server is under control.

like image 468
user3088260 Avatar asked May 15 '26 22:05

user3088260


1 Answers

Well you could use some template library like handlebars and use jquery to facilitate the element selection, example:

<div id="target"></div>

<script id="hi-template" type="text/x-handlebars-template">
  Hi {{userName}}
</script>

<script type='text/javascript'>
    var template = Handlebars.compile($("#hi-template").html());
    $('#target').html(template({userName: "bob"}));
</script>
like image 173
ifm Avatar answered May 17 '26 11:05

ifm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!