-1

I'm attempting to use .text() on multiple (unknown number of) elements on a page.

Consider:

<div class="myClass">element1</div>
<div class="myClass">element2</div>
<div class="myClass">element3</div>

and

$(document).ready(function(){
    $( ".myClass" ).click(function() {
        var text = $('.myClass').text()
        alert(text)
    });
});

The problem is, the .text() will return all the elements at the same time (in this example: "element1element2element3").

I'd need to return only the text within the clicked class, for example: click on element2, it returns "element2" as .text().

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
jeandav
  • 59
  • 5

4 Answers4

4

Context is key.

Event callbacks are run in the context of the trigger element. In other words, this points to that element. So instead of repeating the selector, as you currently are (unnecessarily wasteful in terms of performance), reference this:

$( ".myClass" ).click(function() {
    var text = $(this).text(); //this === the clicked element
    console.log(text);
});
Mitya
  • 33,629
  • 9
  • 60
  • 107
0

Use $(this):

$(document).ready(function(){
    $(".myClass").click(function() {
        var text = $(this).text();
        console.log(text);
    });
});

Inside event callback this refers to the current (i.e. clicked) element.

Also, console.log() is better for debugging than alert().

Community
  • 1
  • 1
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
0

Although there are answers already been posted but I would post mine with little explanation:

See, currently you have bound an event on class selector and in the web browser class selector returns a collection. So, that means there will be more than one element in the list.

More additions to this there are tag name selectors too which also returns a collection.

While on the other selector ID selector returns only one element always because as per standards or better to say as per rule IDs should have to be unique for each element. And that's why it always returns a single element from the DOM.

That's the reason you get different behavior. To overcome this issue you need to understand the context of the selector. Which is a good topic to get info about this.

So, this represents the DOM node and in your case you need jQuery object. So, wrap it with jQuery wrapper $() to have a jQuery object with $(this).

$( ".myClass" ).click(function() {
    var text = $(this).text(); // the elem in context
    console.log(text);
});
Jai
  • 74,255
  • 12
  • 74
  • 103
0

You can use the event object to find out which element is clicked and then can show it's text

$(document).ready(function(){
    $( ".myClass" ).click(function(event) {
        var text = $(event.target).text()
        alert(text)
    });
});

JSFIDDLE

brk
  • 48,835
  • 10
  • 56
  • 78