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>
You have to use $('#li-id'). find('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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With