0

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>

2
  • If you want to alert "Sold out", why not just alert that directly? Commented Mar 23, 2017 at 0:44
  • @Pytth It's obviously a simplification of his actual task, where the text will be variable. Commented Mar 23, 2017 at 0:47

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.