views:

35

answers:

3

When I click on a div, I would like to change the text inside it to New Text.

How can I do that with jquery

$('#mydiv').????
+3  A: 
$('#mydiv').click(function(){
    this.innerHTML = "New Text";
});

crazy demo

if you have something to chain, you can do it this way,

$('#mydiv').click(function() {
    $(this).html("New Text") // can include html tags, use .text() for text only.
        .animate({marginLeft: '+=10'}); // chain an animation...
});

crazy demo

Reigel
"Cwaaaazy good" — Sgt. Angel Batista
Alec
Is there any difference between `.innerHTML` and `.html` as answered by @kchau
vinny
@vinny - `.innerHTML` is a property of a `DOM` element while `.html` is a jQuery method. Native browser method or property is way faster than any javascript framework's method.
Reigel
.html is forgiving of manipulating a table's contents and so forth.
wombleton
+1  A: 
$('#mydiv').click(function() {
    $(this).html("New Text");
});
kchau
Is there any difference between `.html` and `.innerHTML` as answered by @Reigel
vinny
@vinny: innerHTML is faster in this case. You don't need a jQuery object to change all contents directly, it's a simple task.
BrunoLM
In either case, the performance difference is negligible... I just used jQuery because that's what your question asked for.
kchau
+2  A: 

Bind an event and handle it:

$('#mydiv').click(function() {
    $(this).html("New Text");
});

Or use bind

$('#mydiv').bind("click", function() {
    $(this).html("New Text");
});

Or live

$('#mydiv').live("click", function() {
    $(this).html("New Text");
});

References

BrunoLM