Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .html() function not working [duplicate]

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.

like image 926
user2352119 Avatar asked Jul 09 '15 01:07

user2352119


2 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();
like image 59
The_Black_Smurf Avatar answered Oct 16 '22 10:10

The_Black_Smurf


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)
...
like image 2
Bikas Avatar answered Oct 16 '22 11:10

Bikas