I have the following mark up code
<!DOCTYPE html> <html> <head> <title>Untitled</title> </head> <body> <table> <tr> <th></th> <th></th> <th>Back</th> </tr> <tr> <td>1.98</td> <td>1.99</td> <td>2.00</td> </tr> </table> </body> <!-- jQuery --> <script src=""></script> </html> I use the following Javascript code to change the values of my "runner-row" elements
window.onload = function() { var gElemRunners = $(".runner-row"); gElemRunners[0].innerHTML = 1.5; gElemRunners[1].innerHTML = 1.6; gElemRunners[2].innerHTML = 1.7; } This code works absolutely fine and the values update properly when the window has loaded. However, the following code does not work.
window.onload = function() { var gElemRunners = $(".runner-row"); gElemRunners[0].html(1.5); gElemRunners[1].html(1.6); gElemRunners[2].html(1.7); } I get the following error in DevConsole
Uncaught TypeError: $(...)[0].html is not a function I get the same error even if I change the .html to .text or .val. Please help me with this because I can't seem to understand where the problem lies.
34 Answers
$(...)[0] will return the DOM element. If you want to use a jquery function, it has to be on a jquery selector object. If you want to get the jquery selector for a specific index, use the eq function:
$('selection').eq(0).html(); 2When you read from jQuery object gElemRunners, you're getting HTMLElement and not the jQuery object. You have to wrap the HTMLElement again to jQuery object before using any of it's function.
Try this instead (also there can be multiple better ways, I'm just suggesting one here) -
$(gElemRunners[0]).html(1.5) ... As already pointed out gElemRunners[0] returns the DOM API, which doesn't have a html method.
What you can use is the jQuery.each() method to iterate over your elements, or you can use gElemRunners.eq(0).html().
The problem is that you are trying to use a jQuery method in a non-jQuery object, because when you get the first element gElemRunners[0], it is returning the DOMElement itself, not the jQuery object.
Using jQuery, you could do:
var gElemRunners = $(".runner-row"); gElemRunners.eq(0).html(1.5); gElemRunners.eq(1).html(1.6); gElemRunners.eq(2).html(1.7);