Ian Vink
Ian Vink

Reputation: 68750

jQuery: html() not available in event?

Newbie question:

I have a web page with a single p element. I thought I could access the p.html() inside an event, but can't. Is there a way to access the element inside the event as a jQuery element?

<script src="Scripts/jquery-1.8.2.js"></script>      
    $(function () {
        $("p").first().bind('click',null, function (event) {
            this.innerHTML = "this works";
            this.html('this does not');
        });
    }
    );

Upvotes: 3

Views: 125

Answers (6)

Ian
Ian

Reputation: 50905

When using this in your context, it's the DOM element. You can use native methods, like innerHTML. html is a jQuery method, which would require you use $(this).html().


References:

Upvotes: 5

Parag Meshram
Parag Meshram

Reputation: 8511

As you are using this, it is a DOM object and 'html' is method of jQuery object.

You need to convert it to jQuery object before using any jQuery api. To convert it simply use $(DOM Object) construct.

Now this will work -

$(function () {
    $("p").first().bind('click',null, function (event) {
        this.innerHTML = "this works";
        $(this).html('this works !!!)');
    });
}
);

According to jQuery API -

$() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements:

$('div.foo');

Here div.foo is DOM element which is this in your case.

Upvotes: 1

Anoop
Anoop

Reputation: 23208

Modified code: this is not a jQuery object.

    $(function () {
        $("p").first().bind('click',null, function (event) {
            this.innerHTML = "this works";
            $(this).html('this will work now');
        });
    }
    );

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

this in handler function is your DOM element.. it doesn't have .html function.. wrap it with $ to make it a jQuery object and do a .html

$(this).html('this does work now');

Full code:

$(function () {
    $("p").first().bind('click',null, function (event) {
       this.innerHTML = "this works";
       $(this).html('this does work now');
    });
});

Upvotes: 7

YogeshWaran
YogeshWaran

Reputation: 2281

this is DOM element ,it is not jquery object .so use $(this)

  $(this).html('this now works');

Upvotes: 0

Kevin Boucher
Kevin Boucher

Reputation: 16675

Try this (nned jQuery object):

$( this ).html()

Upvotes: 0

Related Questions