Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Get content of clicked span by class

Tags:

jquery

I've got several span tags, with the same class. Every span has it's unique id. Now I'd like to get the content and the id of the clicked span class.

I found out how I go about the id of the class, but I can't seem to get the content between the <span></span> tags. I tried this.html(), this.html, this.text and this.tex() but I can't get the text.

$(".row").click(function() {
    alert(this.id);
    alert(this.html);
}

HTML :

<div>
    <span class="row" id="1">Username of user 1</span>
    <span class="row" id="2">Username of user 2</span>
<div>
like image 602
Ahatius Avatar asked May 30 '12 07:05

Ahatius


People also ask

How get Li span value in JQuery?

You have to use $('#li-id'). find('span').

How do you value a span?

Use the textContent property to get the text of a span element, e.g. const text = span. textContent . The textContent property will return the text content of the span and its descendants. If the element is empty, an empty string is returned.


1 Answers

Your id's are invalid (they cannot start with a digit), so change them and try this

<div id="parent">
    <span class="row" id="s1">Username of user 1</span>
    <span class="row" id="s2">Username of user 2</span>
    ...
</div>

jQuery

$("#parent").on('click', '.row', function() {
    alert(this.id);
    alert(this.innerHTML);
});

doing so you will use event delegation, capturing the click event on the parent and defining the handler just once (and not, expensively, for every span)

like image 105
Fabrizio Calderan Avatar answered Oct 06 '22 18:10

Fabrizio Calderan