DOM Manipulation
Learn how to get and set text content of elements in YakaJS. The .text() method provides a simple way to work with plain text, automatically handling encoding and multiple elements.
.text()Get the text content of the first element in the collection.
Returns: String containing the text content
Examples:
// Get text from a single elementconst heading = _('#title').text();console.log(heading); // "Welcome to YakaJS"// Get text from first element in collectionconst firstParagraph = _('p').text();console.log(firstParagraph); // Text from first <p>// Get text from nested elementsconst articleText = _('#article').text();// Returns all text content, including nested elements.text(value)Set the text content of all elements in the collection.
Parameters:
value (string | number | function): Text to set or function returning textReturns: YakaJS collection (for chaining)
Examples:
// Set simple text_('#title').text('New Title');// Set text on multiple elements_('.price').text('$99.99');// Set text with numbers_('#count').text(42);// Clear text_('#message').text('');Pass a function to set text based on current content or index.
// Function receives (index, currentText)_('.item').text(function(index, currentText) { return `Item ${index + 1}: ${currentText}`;});// Add prefix to all paragraphs_('p').text(function(i, text) { return `Note: ${text}`;});// Transform text_('.uppercase').text(function(i, text) { return text.toUpperCase();});The .text() method handles only plain text and automatically escapes HTML.
// Set text (HTML is escaped)_('#content').text('<strong>Bold</strong>');// Result: <div id="content"><strong>Bold</strong></div>// To set HTML, use .html() instead_('#content').html('<strong>Bold</strong>');// Result: <div id="content"><strong>Bold</strong></div>// Get text from first elementconst firstText = _('p').text();// Set text on all elements_('p').text('Same text for all paragraphs');// Set different text for each element_('li').text(function(index) { return `List item #${index + 1}`;});// Iterate to handle each individually_('.item').each(function(index, element) { _(element).text(`Item ${index}`);});// Append to existing textconst current = _('#message').text();_('#message').text(current + ' - Updated');// Using function_('#message').text(function(i, text) { return text + ' - Updated';});// Prepend to existing text_('#message').text(function(i, text) { return 'Important: ' + text;});// Replace part of text_('p').text(function(i, text) { return text.replace('old', 'new');});// Replace with regex_('.code').text(function(i, text) { return text.replace(/\d+/g, 'X');});// Uppercase all_('.uppercase').text(function(i, text) { return text.toUpperCase();});// Capitalize first letter_('.capitalize').text(function(i, text) { return text.charAt(0).toUpperCase() + text.slice(1);});// Trim whitespace_('p').text(function(i, text) { return text.trim();});YakaJS automatically handles special characters and encoding.
// Special characters are preserved_('#content').text('Price: $99 & free shipping');// Unicode characters work_('#unicode').text('😊 Hello 世界');// Newlines are preserved in text_('#multiline').text('Line 1\nLine 2\nLine 3');// Quotes are safe_('#quote').text("It's a 'great' day!");// Check for empty textconst text = _('#element').text();if (text === '') { console.log('Element has no text');}// Check if element existsif (_('#element').length === 0) { console.log('Element does not exist');}// Setting undefined or null clears text_('#content').text(undefined); // Clears text_('#content').text(null); // Clears text// Bad: Multiple queries_('#title').text('New Title');_('#title').addClass('active');_('#title').on('click', handler);// Good: Cache selectionconst title = _('#title');title.text('New Title');title.addClass('active');title.on('click', handler);// Bad: Individual updates_('.item').each(function(i) { _(this).text(`Item ${i}`);});// Good: Single update_('.item').text(function(i) { return `Item ${i}`;});let count = 0;_('#increment').on('click', function() { count++; _('#counter').text(count);});_('#search').on('input', function() { const query = _(this).val(); const results = _('.item').filter(function() { return _(this).text().toLowerCase().includes(query.toLowerCase()); }); _('#result-count').text(`Found ${results.length} results`);});const messages = ['Loading', 'Loading.', 'Loading..', 'Loading...'];let index = 0;setInterval(() => { _('#loading').text(messages[index++ % messages.length]);}, 500);_('#email').on('blur', function() { const email = _(this).val(); if (!email.includes('@')) { _('#error').text('Please enter a valid email address'); } else { _('#error').text(''); }});_('#comment').on('input', function() { const length = _(this).val().length; const remaining = 280 - length; _('#char-count').text(`${remaining} characters remaining`);});const hour = new Date().getHours();let greeting;if (hour < 12) greeting = 'Good morning';else if (hour < 18) greeting = 'Good afternoon';else greeting = 'Good evening';_('#greeting').text(`${greeting}!`);YakaJS .text() works identically to jQuery:
| jQuery | YakaJS |
|--------|--------|
| $('#el').text() | _('#el').text() |
| $('#el').text('New') | _('#el').text('New') |
| $('.cls').text(fn) | _('.cls').text(fn) |
.html()