Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
        });
    }
    );
like image 567
Ian Vink Avatar asked Dec 09 '25 16:12

Ian Vink


2 Answers

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');
    });
});
like image 166
Selvakumar Arumugam Avatar answered Dec 12 '25 06:12

Selvakumar Arumugam


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.innerHTML
like image 35
Ian Avatar answered Dec 12 '25 06:12

Ian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!