George Smith
George Smith

Reputation: 505

jQuery - .text returns [Object Object] instead of a variable.

I am trying to write a simple script which goes div by div and changes the text of that div to "Sold out". However, the .text is returning [Object, Object] instead of "Sold out". I will be very grateful if someone can tell me what I am doing wrong. Thank you in advance.

Best regards, George

$(function Store(){

    Status = "Sold out";
    
    $("div").each(function(){
        $(this).contents().not($(this).children()).text(Status);
        alert($(this).contents().not($(this).children()).text(Status));
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<div id="Wallet">
    <div class="Price">
        10.00$
    </div>
    <div class="Price">
        20.00$
    </div>
    <div class="Price">
        30.00$
    </div>
</div>

Upvotes: 0

Views: 2229

Answers (1)

Barmar
Barmar

Reputation: 780843

When you give an argument to .text(), it doesn't return the text, it sets the text. And it returns the jQuery object so that the method can be chained.

If you want to display the text, leave out the argument.

$(function Store(){

    Status = "Sold out";
    
    $("div").each(function(){
        $(this).contents().not($(this).children()).text(Status);
        alert($(this).contents().not($(this).children()).text());
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<div id="Wallet">
    <div class="Price">
        10.00$
    </div>
    <div class="Price">
        20.00$
    </div>
    <div class="Price">
        30.00$
    </div>
</div>

This isn't alerting Sold out, though. I think this is because .text(Status) isn't able to set the text of text nodes. If you can, you should redesign your HTML so you have a <div> or <span> where you put the Sold out message, rather than using .contents() to access the text nodes.

Upvotes: 3

Related Questions