Ty M
Ty M

Reputation: 184

Access inner text using $(this) with jQuery

I have a button and I want to log the inner text using the jQuery when that button is clicked. I know how to use the id to get the text of the buttton ($("#testID").text()), but that's not an option for me. I would like to use the $(this) keyword instead of the id, but I'm not sure how to do that.

The html:

<button id="testID" onclick="getButtonText()">Button Text</button>

The javascript:

function getButtonText() {
    console.log("this text = " + $(this).text()); //not working
}

Upvotes: 0

Views: 1633

Answers (3)

GunWanderer
GunWanderer

Reputation: 324

You can give it a class on the button and then whenever a class is click, it will determine the DOM, which is $(this). Example:

In your html file: <button id="testID" class="test-btn">Button Text</button>

In your script file:

$(document).ready(function () {
$(".test-btn").click(function(){ $("#message").text("The Text is: " + $(this).text() ); }); });

See my example on Plunker: http://plnkr.co/edit/e94QraQfCOzGlkirvTJj?p=preview

Upvotes: 0

Turnip
Turnip

Reputation: 36732

You need to pass the caller element to the function...

function getButtonText(element) {
    var $this = $(element);
    console.log("this text = " + $this.text());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button id="testID" onclick="getButtonText(this)">Button Text</button>

Though the proper jQuery way of doing it would be like this...

$('#testID').on('click',function() {
  console.log("this text = " + $(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button id="testID">Button Text</button>

Upvotes: 4

AmmarCSE
AmmarCSE

Reputation: 30607

Pass in this

The html:

<button id="testID" onclick="getButtonText(this)">Button Text</button>

The javascript:

function getButtonText(self) {
    console.log("this text = " + $(self).text()); //not working
}

Otherwise, this will be the window object

Upvotes: 3

Related Questions