1

I am attempting to add values within a script tag and reading it and parsing the values in JavaScript. I have something like this in my HTML file.

<script type="text/plain" id="bound-bunny">
v -0.069188 0.091379 -0.013998
v -0.266134 0.287866 0.204836
v 0.150992 0.147769 0.133125
</script>

And I would like to read the values within script tag and eventually parse it.

var me = document.getElementById('bound-bunny').innerHTML;
console.log(me);

I have done something like this, but I am getting Cannot read property 'innerHTML' of null so I am not sure how to proceed.

2 Answers2

1

Your code is fine, make sure that <script type="text/plain" id="bound-bunny"> is loaded, and executed before the moment of execution document.getElementById('bound-bunny').innerHTML

Examples:

This example will work fine because of #running-script is being executed after the #bound-bunny

<script type="text/plain" id="bound-bunny">
v -0.069188 0.091379 -0.013998
v -0.266134 0.287866 0.204836
v 0.150992 0.147769 0.133125
</script>

<script id="running-script">
var me = document.getElementById('bound-bunny').innerHTML;
console.log(me);
</script>

This example will throw the same error as you have because of #running-script is being executed before the #bound-bunny

<script id="running-script">
var me = document.getElementById('bound-bunny').innerHTML;
console.log(me);
</script>

<script type="text/plain" id="bound-bunny">
v -0.069188 0.091379 -0.013998
v -0.266134 0.287866 0.204836
v 0.150992 0.147769 0.133125
</script>
qiAlex
  • 3,794
  • 2
  • 11
  • 30
-1

You could parse the variables from the tag. Though calling it a script tag wouldn't be appropriate.

You could also just have the values inside the script as valid javscript variables:

<script type="text/javascript">
const vars = [
    {-0.069188, 0.091379, -0.013998},
    {-0.266134, 0.287866,0.204836},
    {0.150992, 0.147769, 0.133125}
]
</script>

Edit: I think I might've misunderstood, if you want to simply read the values instead of actually parsing them as valid JavaScript variables, your code is fine. Just make sure the JavaScript code is in a script tag placed after the "bound-bunny" tag. This way you make sure that the tag with the values is loaded before it's accessed.

Rein F
  • 188
  • 2
  • 7