Access a button's properties inside its click event handler

- 1 answer

Ad

A button:

<button class='button pasteButton' id='pasteButton1'>Button Label</button>

The button's click handler:

$(document).on('click','.pasteButton',function(e){

    //alert("paste clicked");
    alert(this.id);

    e.preventDefault();
});

I'm able to get the button's id inside the click handler with the above code. How may I get the button's value (i.e., "Button Label") or some other property inside the click handler?

(And while we're on the subject, why is it that with jQuery sometimes we need to do: this (e.g., above) and at other times we need to do: $(this) ... is there a simple explanation of the difference please?

Ad

Answer

Ad

If you want to retrieve the text, either access the textContent property on the DOM element:

this.textContent // Button Label

Or use the jQuery .text() method:

$(this).text() // Button Label

Why is it that that with jQuery sometimes we need to do: this (e.g., above) and at other times we need to do: $(this)

In this case, this is a DOM element, whereas $(this) is a jQuery object.

Native DOM element have properties, such as value, id, textContent.

this.id // pasteButton1
this.textContent // Button Label

It's worth pointing out that you can't use jQuery methods directly on DOM elements, which is why you wrap this with $() in order to turn it into a jQuery object.

$(this).prop('id') // pasteButton1
$(this).text() // Button Label
Ad
source: stackoverflow.com
Ad