0

// Function for setting text of an element:
function setText(elementId, message) 
{
    'use strict';
    
     
if ( (typeof elementId == 'string')&& (typeof message == 'string') ) 
   {
      var output = $(elementId);
    if (output.textContent !== undefined) 
     {
      output.textContent = $(elementId).string;
      } 
     else 
     {
      output.innerText =$(elementId).string ;
    }
     
   } // End of main if.
} // End of setText() function.

I need help with this code, I need to define a function name the setText() function as shown below, when I run this code in JS Bin the page shows the code won't run, I couldn't find where the error is. Can anyone give me a hint?

Xixi Li
  • 3
  • 2
  • If $ denotes jQuery, $(elementId) (I assume by that you mean any element identification, not just literal IDs) will return a collection. A collection (array) doesn't have the innerText property, individual members do. You need to iterate over the collection. – Petr Skocik Apr 10 '15 at 00:14

2 Answers2

0

Your type checking for message is unnecessary, but in case you want to keep it:

function setText(elementId, message){
    if((typeof elementId == 'string') && (typeof message == 'string')){ 
        document.getElementById(elementId).innerHTML = message;
    }
}

setText("foo", "1")
setText("foobar", "2")
setText("bar", "3")
setText("barfoo", "4")
<p id="foo"></p>
<p id="foobar"></p>
<p id="bar"></p>
<p id="barfoo"></p>
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • thank you for the hits, actually my code is just to run with random string, I was look at my book, i think i was missing the reference variable – Xixi Li Apr 10 '15 at 00:20
  • This code is susceptible to XXS. rather than setting the `innerHTML` set the `text` `document.getElementById(elementId).textContent = message;` is safer for modern browsers. See more here: http://stackoverflow.com/questions/1358810/how-do-i-change-the-text-of-a-span-element-in-javascript – alexreardon Apr 10 '15 at 00:32
  • @alexreardon thank you for the reference, i will use for next code, the textContent was kind confuse for me – Xixi Li Apr 10 '15 at 03:15
0

You can do it using JavaScript prototypical way. This is little advanced.

HTML:

<span id="spanText"> Your sample Text </span> 

First of all augment the type by this code:
/* Augmenting type */

Function.prototype.addMethod = function(funcName, funcBody){
if(!this.prototype[funcName]){
    this.prototype[funcName] = funcBody;
    return this;
}};

String.addMethod("setText", function(text){
    document.getElementById(this).textContent = text;
});

var elementId = "spanText";
elementId.setText("kkkkkkkkkkk");

Load this JS below your HTML file. You are able to add any of your custom string, number, array method by this way. See the complete example here: https://jsfiddle.net/dmsbilas/wu3cd88w/