Explain Codes LogoExplain Codes Logo

$(this).val() not working to get text from span using jquery

javascript
event-handling
jquery
selectors
Nikita BarsukovbyNikita Barsukov·Nov 4, 2024
TLDR

To get the text content from a <span> element, you should use $(this).text(), not $(this).val(). Here’s a simple illustration:

var spanText = $(this).text(); // Stores the span text in a variable

Ensure that the <span> elements you're aiming for are directly targeted:

$(".mySpan").text(); // A-okay! Picks the text from a class called "mySpan"

Beware of trap: If the <span> is dynamically generated, the correct event binding is the way to go:

$(document).on('click', '.dynamic-span', function () { let spanText = $(this).text(); alert(spanText); // Alert message with the span's text content });

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>.
$("#inputForm").val(); // Does exactly what it looks like (gets input values) $("#spanElement").text(); // Also does exactly what it looks like (gets span text)

When .html() is the Hero

Need more than just the text from the <span> element? Perhaps HTML tags too? .html() is your guy:

var yourSpanHtml = $("#coolSpan").html(); // Gets HTML content along with the text

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.

$("body").on('click', '#dynamicSpan', function() { // I'm dynamic and I know it! });

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:

var spanTextFallback = $(this).parent().find('span')[0].innerText; // Pheeew...!

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:

$(document).on('click', '.ui-datepicker-month', function () { console.log($(this).text()); // Hello, Mr. Month! Nice to see ya. });

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:

$("body").on('click', '.childSpan', function() { // Knock knock, who's there? It's your dynamic child! });