Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You're passing a string, not a variable, use:</p> <pre><code>onclick="myFunction(data)" </code></pre> <p>A string must be quoted, a variable (a reference, in this case, to a string) must not (otherwise it'll be assessed as a literal string).</p> <p>Incidentally, JavaScript doesn't require you to explicitly create a string before assigning a value to it, you could use just:</p> <pre><code>var data = 'This is what I want to show.'; </code></pre> <p>And while using <code>innerHTML</code> works, if all you're doing is updating text content (and there are no nested nodes to be considered) you could simply use:</p> <pre><code>function myFunction(text) { // the var declaration prevents the variable becoming global var elem = document.getElementById('replace'); elem.appendChild(document.createTextNode(text)); } </code></pre> <p>And to make it more generally-useful, avoid hard-coding the <code>id</code> of the element to change within the function, instead pass it to the function:</p> <pre><code>function myFunction(text, elem) { // testing if the element is a node, if not assume it's a string of the id: var elem = elem.nodeType === 1 ? elem : document.getElementById('replace'); elem.appendChild(document.createTextNode(text)); } </code></pre> <p>And coupling the above with:</p> <pre><code>onclick="myFunction(data, 'replace')" </code></pre> <p>Or:</p> <pre><code>onclick="myFunction(data, document.getElementById('replace'))" </code></pre> <p>I'd also, strongly, advise not using in-line/obtrusive JavaScript, simply to make it easier to update the functions to be called, the arguments and the functions themselves, in one place (rather than having to navigate through the document and finding every instance in which the function is called):</p> <pre><code>// define the function here var buttons = document.getElementsByTagName('button'), replace = document.getElementById('replace'), data = 'Text I want to show.'; for (var i = 0, len = buttons.length; i &lt; len; i++){ buttons[i].onclick = function(){ myFunction(data, replace); }; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload