-1

Is there any way to save a javascript tag in an HTML object? What I would like to do is something like this:

<div id="htmlTag">some text</div>
<script type="text/javascript">
    htmlTag.something = {s:"a string",n:1,b:false,a:[3,2,1],f:function(){alert("hello")}}
</script>
Donald Duck
  • 8,409
  • 22
  • 75
  • 99

3 Answers3

1

You can convert JS objects to JSON string with this plugin, if that is what you want to achieve.

var json_data = JSON.stringify(yourObj);
Ales Maticic
  • 1,895
  • 3
  • 13
  • 27
1

I think your only problem is you're not getting the node.

document.getElementById("htmlObject").something = {hi: 1};
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
tanenbring
  • 780
  • 4
  • 14
0

You can do this using the javascript function JSON.stringify()

Javascript

<div id="htmlTag">some text</div>
<script type="text/javascript">
    document.getElementById('htmlTag').something = JSON.stringify({s:"a string",n:1,b:false,a:[3,2,1],f:function(){alert("hello")}});
</script>

Here is a JSFiddle : https://jsfiddle.net/LcrLeg8a/1/

Sofiene Djebali
  • 4,398
  • 1
  • 21
  • 27
  • You actually don't need to stringify. Node elements are treated similar to regular js objects, so you can add arbitrary properties to it. – tanenbring May 24 '16 at 16:44