Reputation: 68750
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
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:
$().html()
- https://api.jquery.com/html/element.innerHTML
- https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTMLUpvotes: 5
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
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
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
Reputation: 2281
this
is DOM element ,it is not jquery object .so use $(this)
$(this).html('this now works');
Upvotes: 0