0

Hello i want to replace the text in div when user click on it i have tried this code but there is something wrong with my code

<script>
$(document).ready(function(){
    //alert('hi');
    $('div').append('hi')

    $('div').click(function(){
        $('this').append('how r u');

        })

    })
</script>

please help

Thanks

1
  • What's wrong with it? Are there any errors? Commented Mar 22, 2012 at 13:07

4 Answers 4

5

You are close!

this is a keyword in JavaScript, but you are using it as a string. Get rid of ' around this and you should be fine!

$('div').click(function(){
    $(this).append('how r u');
});

Note

If you want to replace the text, you should use .html() or .text() instead of .append(). Append will leave all text in the div as it is, and add the new text at the end.

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

Comments

2

If you want to replace the text, use the html method

$('div').click(function(){
        $(this).html('how r u');

        })    
})

you dont need' with this.

working sample : http://jsfiddle.net/4xj72/1/

you can use text() method as well if there is no HTML markups you are adding.

http://jsfiddle.net/4xj72/3/

Comments

1
    <script>
$(document).ready(function(){
    //alert('hi');
    $('div').append('hi')

    $('div').click(function(){
        $(this).append('how r u');

        })

    })
</script>

Comments

1

$('this').append('how r u'); should $(this).append('how r u');. this is a keyword there should not be ' quotes around it.

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.