mightyspaj3
mightyspaj3

Reputation: 471

jQuery .html() is returning as 'undefined'

For some reason when I use html() it returns as undefined. Using text() doesn't work either.

I've searched through the internet as well as stackoverflow, and all of the answers have not solved my problem. I'm a novice a jQuery, so please be easy on me :)

Here's my code:

jQuery:

$("#cartBtn").on("click", function() {
    var total = $("#cart_cost").html();
    $("#total").append(total);
});

HTML:

<td id="cart_cost" class="text-right">$10</td>

<a id="total">Total: </a>

Upvotes: 0

Views: 1997

Answers (2)

shukshin.ivan
shukshin.ivan

Reputation: 11340

Sometimes .html() can be undefined due to bad html when initializing jquery object

var obj = $('<!-- sad --><div>hello</div>');
console.log(obj.html())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

Upvotes: 0

Danyial Shahid Ali
Danyial Shahid Ali

Reputation: 511

problem In Your html Codes

 td Work Inside in table

if td has Not Is Parent table td Not Parse By jQuery

   $(document).ready(function(){
        var total = $("#cart_cost").html();
        alert(total);
        $("#total").append(total);
    });

Simply Add Table Tag Outer Of td Tag

 <table>
    <td id="cart_cost" class="text-right">$10</td>
    <a id="total">Total: </a>
    </table>

Upvotes: 1

Related Questions