2

I have a dynamically generated html table whose columns have id assigned dynamically. for ex:

   <td id="1">1</td>
    <td id="2">2</td>
     ....
     ....
   <td id="n">n</td>

in order to get the get value of a specific column I am using document.getElementById("#myvar").innerHTML or $("td#myvar").html where myvar is variable that contains search element such as 2 or 3 etc. But I dont get any results. If I direcly use a number for document.getElementById("#2").innerHTML , it works. Please advise what to do to get value where id of element is same as the variable declared??

Royi Namir
  • 131,490
  • 121
  • 408
  • 714
JSFan
  • 93
  • 1
  • 6

4 Answers4

5

First, the getElementById() DOM method expects an ID, not a jQuery selector.

Second, neither JavaScript nor jQuery provide variable interpolation in strings, as you seem to be assuming. You have to build your own string:

var myvar = 2;
$("td#" + myvar).html()

Last but not least, remember that the ID attribute cannot start with a digit unless you are using HTML 5.

Community
  • 1
  • 1
Álvaro González
  • 128,942
  • 37
  • 233
  • 325
3

use this -

$("#"+myVar).html();
Avisek Chakraborty
  • 7,971
  • 10
  • 46
  • 75
3

Your code is wrong. When using document.getElementById, you don't include the # sign. When using jQuery id selectors, you do use the # sign, but you need to call .html() as a function.

document.getElementById("myvar").innerHTML

$('#myvar').html(); 

If myvar is a variable, omit the quotes, for instance if myvar = "2"; then your selectors would be:

document.getElementById(myvar).innerHTML

For jQuery, use string concatenation:

$('#' + myvar).html();
jmort253
  • 32,054
  • 10
  • 92
  • 114
1

document.getElementById accepts a string argument which is the id of the element you'd like to select, so you won't need to include #, i.e.

document.getElementById(myvar).innerHTML

Should work

Not directly related to your question, but it is invalid for an ID attribute to start with a number

http://www.w3.org/TR/html401/types.html#type-name

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Andreas Wong
  • 55,398
  • 19
  • 100
  • 120