5

I typically see version 1 but some open source projects I work on use version 2 and I've used version 3 in the past. Does anyone have a more elegant solution, maybe one that's more scalable?

Version 1:

var text1 = 'this is my script\'s content';

Version 2:

<script type="text/plain" id="text1">This is my content</script>
<script> var text1 = $('#text1').html(); </script>

Version 3:

<input type="hidden" id="text1" value="this is my content">
<script> var text1 = $('#text1').val(); </script>

Version 4:

<span class="hidden" id="text1">this is my content</span>
Ryan Detzel
  • 5,519
  • 9
  • 37
  • 49
  • I guess it depends on the size of the text. Long text with line breaks are a bit tedious in JavaScript (because you cannot have multi-line strings). The third way seems to abuse form elements as data containers. Obviously assigning text directly to a variable is "faster" than reading it from the DOM. – Felix Kling Dec 27 '12 at 13:06

3 Answers3

7

v1, because it is the ONLY way to store text in JavaScript. Everything else you've listed is storing text in DOM.

DOM is "presentation" and it is generally bad idea to mix "data" and "presentation". For example when you implement collision in 3D FPS, you will never scan models from screen (presentation), you'll compare their coordinates in their data instead.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
4

I've never used v2. I only use v3 & v4 when communicating with backend, in case they need to send me a variable to be used in my JS. But for anything I work on, I use v1 - there's no need to pollute your html. Separation of interaction and content. Also, I switch between double and single quotes depending on my content. No need for all the escape slashes.

Syon
  • 1,604
  • 13
  • 16
0

storing text as in version 1 is good as rest store data in DOM

iJade
  • 23,144
  • 56
  • 154
  • 243