-2

This is my index.js file:

 function fun()
{
 var obj;
}

This is my index.html file:

<script>
  src="js/index.js"
</script>

I want to use variable obj here.

I saw some solutions to create a variable and pass in index.html but is there any way of injection?

Actually, obj is a JSON object. I forgot to mention that previously. How would I use the JSON object keys and values in my index.html outside of the script tag?

6
  • obj is local to the fun() function. Where are you trying to use it? Commented Aug 15, 2017 at 19:01
  • A variable cannot be used outside of script tags in HTML. Also, your script needs to have the source attribute inside the tag. Commented Aug 15, 2017 at 19:01
  • Possible duplicate of Can a JavaScript variable be used in plain HTML? Commented Aug 15, 2017 at 19:06
  • @MikeMcCaughan i think for my question its not totally apt Commented Aug 15, 2017 at 19:12
  • What do you mean by JSON object? Is it string? Commented Aug 15, 2017 at 19:16

2 Answers 2

0

Try out AngularJS. With this, you can declare variables in $scope and use it in your html like:

JavaScript:

...some angular logic...
$scope.foo = "bar";
...some other angular logic...

HTML:

<p>{{foo}}</p>

There are many tutorials out there. Read the documentation. It may be what you are looking for.

Sign up to request clarification or add additional context in comments.

Comments

0

Although there isn't any way to inject a JS variable into HTML simply, you can use a javascript function to do the same thing:

In index.js:

function fun()
{
    return obj; // Assuming obj is a defined variable.
}
document.getElementById("toReplace").innerHTML = fun();

In index.html

<p id="toReplace"></p>
<script src="index.js"></script>

Essentially, your javascript will replace the content of the <p> tag, which has the ID "toReplace", with the value of fun().

1 Comment

Make sure the DOM is ready, or call the script below the p-tag.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.