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');
});
}
);
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');
});
});
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.innerHTMLIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With