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 class="runner-row runner-back">1.98</td>
<td class="runner-row runner-back">1.99</td>
<td class="runner-row runner-back runner-back-active">2.00</td>
</tr>
</table>
</body>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></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.
$(...)[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();
When 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)
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With