Changing label text dynamically is a common requirement in web development. It allows creating interactive forms, updating elements based on user input, and improving overall UX.
In this comprehensive guide, we will explore various methods to update label text using pure JavaScript as well as jQuery.
Why Change Label Text Dynamically?
Here are some common use cases for changing label text in JavaScript:
Interactive Forms
Updating label text based on user input selection allows creating smart questionnaires and assessments.
For example, changing the next question label based on the previous answer provides an interactive assessment experience:
// Get previous answer
var ans = getPreviousAnswer();
if (ans == "Yes") {
// Show relevant next question
label.innerText = "Why did you say yes?";
} else {
label.innerText = "Why did you say no?"
}
As per a 2022 survey by Forms Designer, over 91% of respondents said dynamic forms improved engagement.
Personalized Elements
Tailoring label text based on user attributes (name, location etc.) enables creating customized UI elements.
For example, welcoming users by their names provides a personalized touch:
// Get logged in user
var user = getLoggedInUser();
// Greet user on label
label.innerText = "Welcome back, " + user.firstName;
As per recent Google research, 61% of users are more likely to return to a site offering personalized experiences.
Notifications and Messages
Updating labels to show success, error or info messages improves overall form UX.
For example:
// Form submission failed
if(!formSubmitted) {
label.innerText = "Error: Form could not be submitted";
}
Smart error handling is critical. 41% of users will abandon a website immediately after a failed transaction as per Baymard Institute.
Conditional Logic
Showing/hiding labels based on certain conditions allows implementing complex business logic easily.
For example:
// User under 18
if(userAge < 18) {
label.innerText = "You must be over 18 to register";
}
Conditional logic can reduce form abandonment. Formstack study found forms with conditional logic can lower abandonment by up to 10-30%.
Localization
Changing labels dynamically enables supporting multiple languages easily.
For example:
if(lang == "es") {
label.innerText = "Introduzca nombre";
} else {
label.innerText = "Enter name";
}
Native language support results in higher conversions. 56% users said they are more likely to buy goods/services on localized sites as per Statista.
Prerequisite Knowledge
Before diving into various methods to change label text, you should have basic understanding of:
- JavaScript DOM manipulation – Accessing and modifying HTML elements
- JavaScript events – Handling interactions like clicks, scrolls
- Basic jQuery selectors and methods – Selecting elements with $() and using text() etc.
- Associating JavaScript code to HTML elements – Event handlers like onclick()
With these core concepts clear, you are ready to learn how to update labels dynamically.
Pure JavaScript Methods
Native JavaScript provides different properties and methods to modify label text:
innerHTML Property
The innerHTML property sets or returns the HTML content of an element.
Here is an example code to change label text using innerHTML property:
// Get label element
var label = document.getElementById("myLabel");
// Change label html text
label.innerHTML = "New label text with <b>bold</b> text";
When above code executes, it will replace existing content and update the inner HTML of myLabel element.
Use Case: Updating labels with formatting like bold, italics etc.
innerText Property
The innerText property sets or returns the text content of an element and its child elements.
Here is an example to change label text using innerText property:
// Get label element
var label = document.querySelector("#myLabel");
// Change text
label.innerText = "New plain text";
When this code runs, it will overwrite existing text content of myLabel element including child nodes with given string.
Use Case: Changing label to plain text. Fast alternative to textContent.
Note:
innerTextalso updates text content of child elements unlikeinnerHTML.
textContent Property
The textContent property is similar to innerText. It sets or returns textual content of an element and its descendants.
Here is an example of using textContent:
// Get label element
var label = document.getElementById("myLabel");
// Update text
label.textContent = "New label text";
When above code executes, it will modify just the direct text content of myLabel element, without touching child elements.
Use Case: Changing text of self node only. Slightly slower than innerText.
Note: Changing
textContentalso modifies text of child elements whileinnerTextdoes not affect child nodes.
value Property
For inputs and textareas, you can change associated label text using value property:
// Get input element
var input = document.getElementById("nameInput");
// Update value
input.value = "John";
// Get assciated label
var label = input.nextElementSibling;
// Modify label text
label.innerText = input.value;
Here label text is updated dynamically based on new value changed for input element.
Use Case: Mirroring input value changes on labels.
Performance Comparison
As per jsPerf benchmarks, setting text content with innerText is significantly faster than textContent in all major browsers today.
But there is no major performance difference between innerHTML and innerText as per UI Dev Labs tests.
| Operation | innerHTML | innerText | textContent |
|---|---|---|---|
| Set | Fast | Fastest | Slightly Slower |
| Get | Fastest | Slower | Slow |
So for performance-critical operations like real-time typing, use innerText to update labels.
jQuery Methods
Along with pure JavaScript, you can also leverage jQuery library to modify labels dynamically.
Benefits of Using jQuery
Some benefits of using jQuery instead of plain JavaScript:
- Cleaner DOM manipulation syntax
- Cross-browser support
- Powerful selectors like class, id etc.
- Animations and effects support
- Lightweight library – only ~83 KB minified
This allows writing less code with wider browser support.
text() Method
The text() method sets or returns visible text content of selected elements.
Here is an example of updating label with jQuery:
$("#myLabel").text("New text set using jQuery");
This will replace existing text with provided string for #myLabel element.
Use Case: Simple way to set plain text.
html() Method
The html() method sets or returns full inner HTML content of selected elements.
Here is an example:
$("#myLabel").html("Text with <strong>bold</strong> style");
This will update #myLabel element with given HTML string having bold styled text.
Use Case: Updating labels with rich text formatting.
val() Method
For textual inputs and textareas, you can utilize val() method to modify label:
// Get input element
var $input = $("#commentBox");
// Update input dynamically
$input.val("User comment");
// Get adjacent label
var $label = $input.next("label");
// Modify label
$label.text("Last updated: " + new Date());
Here label text is changed on updating input value to reflect last updated timestamp.
Use Case: Mirror input changes to label dynamically.
Impact on Accessibility
Changing labels dynamically can impact accessibility of your web app.
Follow these practices to ensure accessibility is not affected:
- Always update
aria-labelattribute alongwith label text - Don‘t solely rely on colors to convey info
- Confirm contrast ratio between label text and background is sufficient
- Don‘t auto-update text too fast for screen readers
- Include additional context if non-text indicators are used
- Enable refreshing page on label text update for older assistive devices
Properly updating ARIA attributes ensures users relying on assistive technologies like screen readers are able to adapt to changed label texts.
Refreshing page also helps older devices detect changed label values updated with JavaScript/Ajax.
Cross-Browser Compatibility
Label text changes using pure JavaScript are supported across all modern & older browsers:
| Method | IE | Firefox | Chrome | Safari | Opera |
|---|---|---|---|---|---|
| innerHTML | IE 8+ | Yes | Yes | Yes | Yes |
| innerText | IE 6+ | Yes | Yes | Yes | Yes |
| textContent | IE 9+ | Yes | Yes | Yes | Yes |
For legacy browser support, using jQuery text modification methods is recommended:
| Method | IE | Firefox | Chrome | Safari | Opera |
|---|---|---|---|---|---|
| text() | IE 6+ | Yes | Yes | Yes | Yes |
| html() | IE 6+ | Yes | Yes | Yes | Yes |
Source: CanIUse.com
jQuery text methods have wider compatibility with patchy old IE versions.
Label Usage Statistics
As per analysis of over 5 million web pages by Semrush:
- 96% of web forms feature labels
- On average each form contains ~15 label elements
- Payment forms have highest density of labels per page – average ~78
- 32% developers prefer innerText over textContent API based on usage
Another study by W3Techs based on top 10 million sites found:
- Labels are used on 84% of websites
- On average each page utilizes labels ~16 times specifically
- Forms account for nearly 62% of total label usage
So labels are extensively used in web applications, especially crucial for forms.
Industry Best Practices
Here are some best practices recommended by pioneers in web forms UX:
Smashing Magazine on Form Design
As per Smashing Magazine style guide:
- Labels should appear before their elements
- Labels shouldn’t be bolded or capitalized
- Use clear language familiar to users
- Follow sequential ordering matching user flow
- Minimize optional fields where possible
UX Planet on Form Optimization
UX Planet journal suggests:
- Mirror validated input values onto labels
- Split long forms into logical sections
- Show updated progress tracker on label changes
- Replace error texts with indicator icons/colors for UX
Baymard Institute
Baymard’s advanced UX research recommends:
- Floating labels reduce data entry time by 13.1% over normal labels
- Top-aligned labels increase completion rates by 4-10% over left-aligned
- Multi-column layout for long forms decreases drop offs by 14.1%
So follow industry-standard label guidelines and form UX principles for best results.
When to Avoid Updating Labels
In certain cases, modifying labels dynamically may degrade user experience:
✘ Don‘t update labels automatically:
- Too frequently causing distraction
- Without user control or permission
✘ Avoid mismatched or incorrect labels:
- Displaying wrong info due to async ops
- Mismatch between label and actual data
✘ Don‘t update hidden or visually blocked labels:
- Visually hidden labels still need changes
- Rotated text must sync correctly
Follow UX best practices around visibility, alignment and accuracy when changing labels programmatically.
Conclusion
Updating label text dynamically helps create great user experiences. JavaScript provides different properties like innerHTML, innerText whereas jQuery offers text() and html() methods for modifying label elements easily.
You should use appropriate text setting approach based on compatibility needs, security concerns and performance objectives for your application.
I hope this comprehensive guide gives you a great overview of how to change label text using plain JavaScript and jQuery like a pro full-stack programmer.
Happy coding!


