JQuery.html () function not working
I have the following markup 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 am using the following Javascript code to change the values ββof the "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 ββare updated correctly when the window is loaded. However, the following code doesn't work.
window.onload = function() {
var gElemRunners = $(".runner-row");
gElemRunners[0].html(1.5);
gElemRunners[1].html(1.6);
gElemRunners[2].html(1.7);
}
The following error appears in DevConsole
Uncaught TypeError: $(...)[0].html is not a function
I am getting the same error even if I change .html to .text or .val. Please help me on this because I can't figure out where the problem is.
source to share
The problem is when you are trying to use the jQuery method on a non-jQuery object, because when you get the first element gElemRunners[0]
, it returns the DOMElement itself, not the jQuery object.
Using jQuery you can do:
var gElemRunners = $(".runner-row");
gElemRunners.eq(0).html(1.5);
gElemRunners.eq(1).html(1.6);
gElemRunners.eq(2).html(1.7);
source to share
As already pointed out, gElemRunners[0]
returns a DOM API that doesn't have an html method.
What you can use is the jQuery.each () method to iterate over your elements or use gElemRunners.eq(0).html()
.
When you read a jQuery object gElemRunners
, you get an HTMLElement, not a jQuery object. You must wrap the HTMLElement with a jQuery object again before using any of its functions.
Try this instead (there might be some better ways too, I just suggest it here) -
$(gElemRunners[0]).html(1.5)
...
source to share