Advanced DOM Manipulation without jQuery
Jul 27, 2025 am 12:52 AMModern JavaScript has replaced jQuery, and can efficiently operate DOM through native APIs. 1. Use document.querySelector() and querySelectorAll() to select elements to support complex selectors; 2. Use event delegates to listen to events in the parent element and use e.target.matches() to judge the target to improve dynamic content performance; 3. Create elements through document.createElement(), or insert HTML with insertAdjacentHTML(); 4. Use setAttribute(), classList and style attributes to operate attributes, class names and styles respectively; 5. Native DOM traversal methods corresponding to jQuery such as parentNode, nextElementSibling, querySelector, etc.; 6. Call el.remove() to delete elements, which can be compatible with old browsers. ParentNode.removeChild(); 7. Use textContent to get or set text content, which is safer and more efficient. InnerHTML is used to insert HTML; 8. Use document.addEventListener('DOMContentLoaded') to wait for the DOM to load; 9. You can write $ and $$ functions to simulate jQuery selectors, and encapsulate $.on to implement event proxy; 10. Performance optimization suggestions include cache selectors, using event delegates, batch DOM operations, and DocumentFragment to reduce rearrangement. With its powerful API, modern JavaScript no longer needs to rely on jQuery, and its code is lighter, efficient and easy to maintain.
Modern web development has largely moved away from jQuery, especially as native JavaScript (ES6 ) and modern DOM APIs have become powerful and consistent across browsers. Advanced DOM manipulation without jQuery is not only possible—it's often faster, cleaner, and more maintained. Here's how to handle common and advanced tasks using vanilla JavaScript.

1. Selecting Elements Like jQuery
jQuery made element selection easy with its flexible $()
syntax. Modern JavaScript offers equally expressive methods:
// Single element (like $('selector').get(0) or $('selector')[0]) const el = document.querySelector('.my-class'); // Multiple elements (returns NodeList, like jQuery collection) const els = document.querySelectorAll('.my-items'); // Match on data attributes, states, etc. const activeLinks = document.querySelectorAll('a.active[data-toggle]');
? Tip : Use Array.from()
or spread syntax to convert NodeList
to an array for map
, filter
, etc.:

const texts = [...document.querySelectorAll('li')].map(li => li.textContent);
2. Event Delegation Without jQuery
Instead of attaching events to each element, use event delegation on a parent—especially useful for dynamic content.
document.addEventListener('click', (e) => { // Check if the clicked element matches a selector if (e.target.matches('button.delete')) { console.log('Deleting item:', e.target.dataset.id); } });
? Works even for elements added later.
? Avoids memory leaks from orphaned event listeners.

3. Creating and Inserting Elements
jQuery: $('<div class="box">Content</div>').appendTo('#container');
Vanilla JS:
const div = document.createElement('div'); div.className = 'box'; div.textContent = 'Content'; document.getElementById('container').appendChild(div);
Or use insertAdjacentHTML()
for quick HTML injection:
document.body.insertAdjacentHTML('beforeend', '<div class="alert">New message</div>');
? Positions: 'beforebegin'
, 'afterbegin'
, 'beforeend'
, 'afterend'
4. Updating Attributes, Classes, and Styles
Attributes
el.setAttribute('data-id', 123); el.getAttribute('href'); el.removeAttribute('disabled');
Classes (with classList
)
el.classList.add('active'); el.classList.remove('hidden'); el.classList.toggle('visible'); el.classList.contains('selected');
Inline Styles
el.style.opacity = '0.5'; el.style.display = 'none'; // For multiple styles, consider using CSS classes instead el.classList.add('fade-out');
5. Traversing the DOM
jQuery made traversal independent. Native equivalents:
jQuery | Vanilla JS |
---|---|
$(el).parent() | el.parentNode |
$(el).children() | el.children (HTMLCollection) |
$(el).next() | el.nextElementSibling |
$(el).prev() | el.previousElementSibling |
$(el).find('.child') | el.querySelector('.child') or el.querySelectorAll() |
Example:
const parent = el.parentNode; const firstChild = parent.firstElementChild; const lastChild = parent.lastElementChild;
6. Remove Elements
jQuery: $('#item').remove();
Vanilla JS:
el.remove(); // Modern browsers
For older browser support:
if (el.parentNode) { el.parentNode.removeChild(el); }
7. Working with HTML and Text Content
Purpose | Method |
---|---|
Get inner HTML | el.innerHTML |
Set inner HTML | el.innerHTML = '<b>new</b>' |
Get text only | el.textContent |
Set text only | el.textContent = 'Plain text' |
?? Use textContent
when possible—it's safer and faster than innerHTML
.
8. Waiting for DOM Ready (Without jQuery Ready)
jQuery: $(document).ready(fn)
Vanilla JS:
document.addEventListener('DOMContentLoaded', () => { console.log('DOM is ready'); });
Or just place your script at the end of <body>
—simple and effective.
9. Custom Utility Function (Mini jQuery Substitute)
If you miss the convenience, write a lightweight wrapper:
const $ = (selector, context = document) => context.querySelector(selector); const $$ = (selector, context = document) => [...context.querySelectorAll(selector)]; // Usage: const header = $('.header'); const links = $$('nav a'); // Add methods $.on = (target, event, selector, handler) => { target.addEventListener(event, (e) => { if (e.target.matches(selector)) handler.call(e.target, e); }); }; // Use it: $.on(document, 'click', '.btn', (e) => alert('Clicked!'));
This gives you jQuery-like syntax without the overhead.
10. Performance Tips
- Cache selectors when used repeatedly.
- Use event delegation for dynamic or large lists.
- Avoid frequently DOM reads/writes— batch changes when possible.
- Use DocumentFragment for inserting many elements:
const fragment = document.createDocumentFragment(); for (let i = 0; i < 100; i ) { const li = document.createElement('li'); li.textContent = `Item ${i}`; fragment.appendChild(li); } list.appendChild(fragment); // One reflow
Basically, modern JavaScript gives you everything jQuery offered—and more—without the extra library. With querySelector
, classList
, addEventListener
, and insertAdjacentHTML
, you can do advanced DOM manipulation cleanly and efficiently.
It's not complex, but it's easy to overlook how far vanilla JS has come.
The above is the detailed content of Advanced DOM Manipulation without jQuery. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Python is an efficient tool to implement ETL processes. 1. Data extraction: Data can be extracted from databases, APIs, files and other sources through pandas, sqlalchemy, requests and other libraries; 2. Data conversion: Use pandas for cleaning, type conversion, association, aggregation and other operations to ensure data quality and optimize performance; 3. Data loading: Use pandas' to_sql method or cloud platform SDK to write data to the target system, pay attention to writing methods and batch processing; 4. Tool recommendations: Airflow, Dagster, Prefect are used for process scheduling and management, combining log alarms and virtual environments to improve stability and maintainability.

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear
