$(this).val() not working to get text from span using jquery
To get the text content from a <span>
element, you should use $(this).text()
, not $(this).val()
. Here’s a simple illustration:
Ensure that the <span>
elements you're aiming for are directly targeted:
Beware of trap:
If the <span>
is dynamically generated, the correct event binding is the way to go:
All about Retrieving Text
The .text() and .val() Conundrum
In case you're going in circles between .text()
and .val()
, let's look at them in a nutshell:
.text()
: The go-to function to retrieve text content from HTML elements like<div>
,<span>
and<p>
..val()
: Only works to grab the value content of form elements, including<input>
,<select>
and<textarea>
.
When .html() is the Hero
Need more than just the text from the <span>
element? Perhaps HTML tags too? .html()
is your guy:
Event Handling Transition
Since the era of jQuery 1.7, .live()
has passed on, and .on()
is the new way to bind event handlers, particularly if you're dealing with dynamically generated elements.
Debugging Corner
Double Trouble?
Is .text()
bringing you unexpected grief? It might be time to check your selectors or switch to vanilla JavaScript for rescue:
HTML Integrity
Sometimes a sleight of hand in the HTML structure can make jQuery selectors stumble. Make sure your DOM structure is clean and accurate.
Pro Tips
Spans by plugins
If your <span>
is birthed by a plugin like jQuery UI's date-picker, don't be afraid. It's still just a span:
Handling Events
To land a perfect punch on performance and for dynamically added elements, bind the event handlers right to a parent element that's sure to exist on page load:
Was this article helpful?