DOM Manipulation
Master DOM manipulation with YakaJS - select, modify, and control elements with ease
Complete guide to selecting and manipulating DOM elements with YakaJS.
_(selector, context)The main YakaJS function for selecting and manipulating DOM elements. Works exactly like jQuery's $() but with more power!
_('#myId') // Select by ID_('.myClass') // Select by class_('div') // Select by tag name_('[data-role="nav"]') // Select by attribute_('<div>Hello</div>') // Create new elements_(document.ready) // DOM ready callbackParameters:
selector (String|Element|Array|Function): The selector, element(s), or callbackcontext (Element, optional): Context element to search withinReturns: YakaJS object for chaining
_('div, p, span') // Multiple selectors_('.class1.class2') // Elements with both classes_('div > .child') // Direct children_('div .descendant') // All descendants.text(value)Get or set the text content of elements.
// Get textconst text = _('#element').text();// Set text_('#element').text('New text content');// Get text from multiple elements (returns array)const texts = _('p').text(); // ['text1', 'text2', ...]Parameters:
value (String, optional): Text to setReturns:
.html(value, sanitize)Get or set the HTML content of elements with optional XSS protection.
// Get HTMLconst html = _('#element').html();// Set HTML_('#element').html('<p>New HTML</p>');// Set with XSS protection (recommended for user input!)_('#element').html(userInput, true); // Sanitizes dangerous tagsParameters:
value (String, optional): HTML to setsanitize (Boolean, optional): Enable XSS protection (default: false)Returns:
Security Note: Always use sanitize: true when setting HTML from user input!
.attr(name, value)Get or set element attributes.
// Get attributeconst href = _('a').attr('href');// Set single attribute_('img').attr('src', 'photo.jpg');// Set multiple attributes_('input').attr({ type: 'text', placeholder: 'Enter name', 'data-id': '123'});// Remove attribute_('div').attr('data-temp', null);.removeAttr(name)Remove an attribute from elements.
_('#element').removeAttr('disabled');_('img').removeAttr('data-loading');.data(key, value)Get or set data attributes (data-*).
// Set data_('#user').data('id', 42); // Sets data-id="42"_('#user').data('role', 'admin'); // Sets data-role="admin"// Get dataconst userId = _('#user').data('id'); // Returns 42const userRole = _('#user').data('role'); // Returns 'admin'// Get all data attributesconst allData = _('#user').data(); // { id: 42, role: 'admin' }.addClass(className)Add one or more classes to elements.
_('#element').addClass('active');_('#element').addClass('active highlight');_('.items').addClass('visible');.removeClass(className)Remove one or more classes from elements.
_('#element').removeClass('active');_('#element').removeClass('active highlight');_('.items').removeClass('hidden');// Remove all classes_('#element').removeClass();.toggleClass(className, state)Toggle one or more classes on elements.
_('#menu').toggleClass('open');_('#theme').toggleClass('dark');// Force add or remove_('#element').toggleClass('active', true); // Always add_('#element').toggleClass('active', false); // Always remove.hasClass(className)Check if element has a class.
if (_('#menu').hasClass('open')) { console.log('Menu is open!');}.css(property, value)Get or set CSS styles.
// Get styleconst color = _('#element').css('color');// Set single style_('#element').css('color', 'red');// Set multiple styles_('#box').css({ width: '200px', height: '200px', backgroundColor: '#3498db', border: '2px solid #2980b9'});.show() / .hide()Show or hide elements.
_('#element').show(); // Sets display to element's default_('#element').hide(); // Sets display to none.toggle()Toggle element visibility.
_('#menu').toggle(); // Shows if hidden, hides if visible.val(value)Get or set form element values.
// Get valueconst inputValue = _('#name').val();// Set value_('#name').val('John Doe');_('#email').val('john@example.com');// Clear value_('#search').val('');.prop(property, value)Get or set element properties.
// Get propertyconst isChecked = _('#checkbox').prop('checked');// Set property_('#checkbox').prop('checked', true);_('#input').prop('disabled', false);// Set multiple properties_('#element').prop({ checked: true, disabled: false});.find(selector)Find descendants matching selector.
_('#container').find('.item');_('ul').find('li.active');.parent()Get the parent element.
_('#child').parent();_('.item').parent(); // Gets parents of all .item elements.children(selector)Get child elements, optionally filtered by selector.
_('#list').children(); // All children_('#list').children('.item'); // Only .item children.siblings(selector)Get sibling elements.
_('#active').siblings();_('#tab1').siblings('.tab');.next() / .prev()Get next or previous sibling.
_('#current').next(); // Next sibling_('#current').prev(); // Previous sibling.closest(selector)Get the closest ancestor matching selector.
_('#button').closest('.container');_('.item').closest('[data-parent]');.append(content) / .prepend(content)Insert content at the end or beginning.
_('#list').append('<li>New item</li>');_('#list').prepend('<li>First item</li>');// Append element_('#container').append(_('<div>').addClass('box'));.after(content) / .before(content)Insert content after or before elements.
_('#element').after('<p>After element</p>');_('#element').before('<p>Before element</p>');.appendTo(target) / .prependTo(target)Append or prepend to target elements.
_('<li>New</li>').appendTo('#list');_('<div>Header</div>').prependTo('#container');.remove()Remove elements from the DOM.
_('#temp-element').remove();_('.old-items').remove();.empty()Remove all child nodes.
_('#container').empty(); // Removes all children, keeps the container.detach()Remove elements but keep data and events.
const element = _('#element').detach(); // Remove but keep in memory// ... later ..._('#container').append(element); // Re-add with events intact.clone(withEvents)Create a deep copy of elements.
// Clone without eventsconst clone = _('#template').clone();_('#container').append(clone);// Clone with eventsconst cloneWithEvents = _('#template').clone(true);_('#container').append(cloneWithEvents);.width() / .height()Get or set element dimensions.
// Get dimensionsconst width = _('#box').width();const height = _('#box').height();// Set dimensions_('#box').width(200);_('#box').height(150);.innerWidth() / .innerHeight()Get dimensions including padding.
const innerWidth = _('#box').innerWidth();const innerHeight = _('#box').innerHeight();.outerWidth() / .outerHeight()Get dimensions including padding and border.
const outerWidth = _('#box').outerWidth();const outerHeight = _('#box').outerHeight();// Include marginconst outerWidthWithMargin = _('#box').outerWidth(true);.offset()Get element position relative to document.
const position = _('#element').offset();console.log(position.top, position.left);.position()Get element position relative to offset parent.
const position = _('#element').position();console.log(position.top, position.left);.scrollTop() / .scrollLeft()Get or set scroll position.
// Get scroll positionconst scrollTop = _('#container').scrollTop();// Set scroll position_('#container').scrollTop(100);_('#container').scrollLeft(50);// Scroll to top_('#container').scrollTop(0);.is(selector)Check if element matches selector.
if (_('#element').is('.active')) { console.log('Element is active');}if (_('#checkbox').is(':checked')) { console.log('Checkbox is checked');}.index()Get the index of element among siblings.
const index = _('#item3').index(); // Returns 2 (0-based).each(callback)Iterate over matched elements.
_('.item').each(function(index, element) { console.log(`Item ${index}:`, element); _(element).addClass('processed');});.map(callback)Create array from matched elements.
const ids = _('.item').map(function(index, element) { return _(element).data('id');});.filter(selector|callback)Filter matched elements.
// Filter by selector_('.item').filter('.active');// Filter by function_('.item').filter(function(index, element) { return _(element).data('id') > 5;});.first() / .last()Get first or last element.
_('.item').first(); // First item_('.item').last(); // Last item.eq(index)Get element at specific index.
_('.item').eq(0); // First item_('.item').eq(2); // Third item_('.item').eq(-1); // Last item.get(index)Get raw DOM element(s).
const element = _('#element').get(0); // Raw DOM elementconst allElements = _('.item').get(); // Array of raw DOM elementsOne of YakaJS's most powerful features is method chaining:
_('#element') .addClass('active') .css('color', 'red') .attr('data-state', 'ready') .text('Hello World') .fadeIn(300);Use .safe() to prevent errors when elements don't exist:
// Traditional way - crashes if element doesn't exist_('#nonexistent').hide(); // ERROR!// Safe mode - silently fails_('#nonexistent').safe().hide().fadeIn().bounce(); // No error!// Enable debug mode for warnings_.debug = true;_('#nonexistent').safe().hide(); // Logs: "Warning: No elements found"Cache selectors for better performance:
const $container = _('#container');$container.addClass('active');$container.css('color', 'red');Use safe mode for optional elements:
_('#optional-element').safe().hide();Sanitize user input when setting HTML:
_('#content').html(userInput, true); // XSS protectionChain methods for cleaner code:
_('#element').addClass('active').fadeIn().css('color', 'red');Use context to improve performance:
$('.item', '#container'); // Searches only within #container