DOM Manipulation
YakaJS provides a powerful jQuery-like selector system for querying and manipulating DOM elements. The core selector function _() supports CSS selectors, context-based queries, and DOM element references.
_(selector, context)The primary way to select elements in YakaJS.
Parameters:
selector (string | Element | NodeList | Array): CSS selector, DOM element, or collectioncontext (Element | string, optional): Context element or selector to limit search scopeReturns: YakaJS collection object with chainable methods
Examples:
// Select by IDconst header = _('#header');// Select by classconst buttons = _('.btn');// Select by tagconst paragraphs = _('p');// Select by attributeconst required = _('[required]');const links = _('a[href^="https://"]');// Complex selectorsconst navLinks = _('nav > ul > li > a');const evenRows = _('tr:nth-child(even)');Limit your selection to a specific part of the DOM for better performance and specificity.
// Select within a context elementconst menuItems = _('.menu-item', '#main-menu');// Using a DOM element as contextconst sidebar = document.getElementById('sidebar');const sidebarLinks = _('a', sidebar);// Nested contextconst container = _('#container');const buttons = _('.btn', container);Select multiple elements at once using comma-separated selectors.
// Multiple selectorsconst elements = _('h1, h2, h3');const inputs = _('input, select, textarea');const media = _('img, video, audio');// Combine with contextconst headerElements = _('h1, h2, h3', '#content');YakaJS supports CSS pseudo-selectors for advanced queries.
// First and last childconst firstItem = _('li:first-child');const lastItem = _('li:last-child');// Nth childconst oddRows = _('tr:nth-child(odd)');const every3rd = _('li:nth-child(3n)');// Empty elementsconst emptyDivs = _('div:empty');// Not selectorconst notDisabled = _('button:not(:disabled)');const notFirst = _('li:not(:first-child)');// Has selectorconst hasImage = _('div:has(img)');// Document_(document).ready(() => { console.log('DOM ready!');});// Window_(window).on('resize', () => { console.log('Window resized');});// In event handlers, 'this' refers to the element_('.btn').on('click', function() { _(this).addClass('clicked');});When you select elements, you get a YakaJS collection object.
// Get the collectionconst items = _('.item');// Check if elements existif (items.length > 0) { console.log(`Found ${items.length} items`);}// Iterate over elementsitems.each((index, element) => { console.log(`Item ${index}:`, element);});// Get specific elementconst firstItem = items.eq(0);const lastItem = items.eq(-1);// Get raw DOM elementconst domElement = items.get(0);// Bad: Re-query every time_('.btn').addClass('active');_('.btn').text('Click me');_('.btn').on('click', handleClick);// Good: Cache the selectionconst buttons = _('.btn');buttons.addClass('active');buttons.text('Click me');buttons.on('click', handleClick);// Slowerconst items = _('div .item');// Faster (more specific)const items = _('#sidebar .item');// Fastest (ID first)const sidebar = _('#sidebar');const items = _('.item', sidebar);// Searches entire documentconst links = _('a');// Only searches within navconst navLinks = _('a', '#nav');YakaJS validates selectors and handles errors gracefully.
// Invalid selector returns empty collectionconst invalid = _(''); // Returns empty collectionconsole.log(invalid.length); // 0// Safe mode prevents crashes_.safe(true);const result = _('invalid[[[selector'); // Won't throw errorAll selector operations return a YakaJS collection, enabling method chaining.
_('.item') .filter(':visible') .addClass('active') .find('.title') .text('Updated Title') .end() .on('click', handleClick);// Build selectors dynamicallyconst type = 'success';const alerts = _(`.alert-${type}`);const id = 'user-123';const user = _(`#${id}`);// Data attributesconst userId = '42';const element = _(`[data-user-id="${userId}"]`);// Check if element existsif (_('#my-element').length) { console.log('Element exists');}// Or use exists() methodif (_('#my-element').exists()) { console.log('Element exists');}// Direct childrenconst directChildren = _('#parent > .child');// All descendantsconst allDescendants = _('#parent .child');// Adjacent siblingsconst nextSibling = _('.item + .item');// General siblingsconst allSiblings = _('.item ~ .item');YakaJS selectors work almost identically to jQuery:
| jQuery | YakaJS |
|--------|--------|
| $('.class') | _('.class') |
| $('#id') | _('#id') |
| $('tag') | _('tag') |
| $('.class', context) | _('.class', context) |
| $(element) | _(element) |
YakaJS selectors use native querySelectorAll under the hood, supporting:
// Select all buttons in a formconst formButtons = _('button', '#my-form');// Select all external linksconst externalLinks = _('a[href^="http"]').filter(function() { return this.hostname !== window.location.hostname;});// Select elements with data attributesconst taggedElements = _('[data-tag]');// Select visible elements onlyconst visibleItems = _('.item:visible');// Select elements by contentconst containsText = _('p:contains("search text")');