Javascript variable as method

L

LukeK1980

is this possible to do or am I dreaming

function getsomething(){
document.write(stuffToGet("myTable","tr","id"))

}

function stuffToGet(elemId,elemArray,valueToGet){
var n, elem =
document.getElementById(elemId).getElementsByTagName(elemArray)
var Nelem = elem.length;
var rS
for (n=0;n<Nelem,n++){
rS= rS + elem[n].valueToGet;
}
return(rS)
}

I want to pass the method in a variable but it doesn't seem to work
for me keep getting and undefined value.
I get the array fine it is only the method that doesn't seem to work

Please help thanks
 
R

RobG

is this possible to do or am I dreaming

function getsomething(){
document.write(stuffToGet("myTable","tr","id"))

}

function stuffToGet(elemId,elemArray,valueToGet){
  var n, elem =
document.getElementById(elemId).getElementsByTagName(elemArray)
  var Nelem = elem.length;
var rS

Initialise rS as a string:

var rS = '';
  for (n=0;n<Nelem,n++){
        rS= rS + elem[n].valueToGet;

Now concatenation will work. You also want valueToGet to be evaluated,
so use square bracket notation:

rS= rS + elem[n][valueToGet];


Also consider making rS an array:

var rS = [];

Then inside the loop:

rS.push(elem[n][valueToGet]);

and lastly:

return rS.join(', ');
}
       return(rS)

Return is not a function, there is no need to wrap the return
expression in brackets.
 
Á

Álvaro G. Vicario

(e-mail address removed) escribió:
function getsomething(){
document.write(stuffToGet("myTable","tr","id"))

}

function stuffToGet(elemId,elemArray,valueToGet){
var n, elem =
document.getElementById(elemId).getElementsByTagName(elemArray)
var Nelem = elem.length;
var rS
for (n=0;n<Nelem,n++){
rS= rS + elem[n].valueToGet;
}
return(rS)
}

I haven't dived into your code but combining document.write() with
document.getElementById() has the drawback that write() can only be used
before the document is finished and getElementById() can only be used
when the element with such ID is ready. You must be careful with that.
 
T

Thomas 'PointedEars' Lahn

Dan said:
for (n=0;n<Nelem,n++){
rS= rS + elem[n].valueToGet;
[...]

Javascript will interpret this as you requesting a property call
valueToGet from the object elem[n]

property _lookup_. Callable objects like Function objects are called instead.
What you need to use is

rS = rS + elem[n][valueToGet];

ACK, or something a little bit more efficient.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,366
Latest member
IanCulpepp

Latest Threads

Top