Reputation: 548
While this seems simple at first glance, I'm having trouble getting what I want. I have many DIVs on a page with the same class which I use to find their text contents:
var Name = $(".class").text();
While this works, it returns all of the text from all DIVs on the page at once such as
Name1Name2Name3Name4Name5
I am calling this request from a jQuery onclick event that is inside one of these DIVs. So my goal is to get the contents of the DIV that the onclick was fired from, not everything. The end result would be if I press the onclick from Name 3 it would only get the contents for that DIV, thus giving me Name3 only.
The DIV does have a unique ID I can also check against but I can't figure out how to use that to my advantage. The DIV structure looks like:
<div id="2242yrcwrmz5t1zyt03" class="class1" tabindex="-1">
Thank you!
Upvotes: 1
Views: 100
Reputation: 1
you can use jQuery parent() method
$(this).parent().text()
heres jsfiddle example https://jsfiddle.net/c628Lwuq/
Upvotes: 0
Reputation: 2944
You can get the element you clicked by using $(this)
$(".class").click(function(){
alert($(this).text());
});
Upvotes: 4
Reputation: 1397
I believe you need to use the event.target
property to find the element that you actually clicked on.
Assuming your DIV that contains Name1, Name2, etc. has the id outerElement
:
$("#outerElement").on("click", function(e) {
var Name = $(e.target).text();
});
More info here: https://api.jquery.com/category/events/event-object/
Upvotes: 0
Reputation: 1849
If you click an element inside the div, you should use
var name = $( this ).parent(".class").text();
Upvotes: 0
Reputation: 148110
Your click event is bubbling up in the DOM hierarchy you need to stop that which could be done by using event.stopPropagation
$('.class1').click(function(event){
alert($(this).text());
event.stopPropagation();
});
Upvotes: 2
Reputation: 207501
So read the text from the current div with this
$(".class").on("click", function() {
console.log($(this).text());
});
Upvotes: 1