<li id="xmsfb"><pre id="xmsfb"></pre></li>

<button id="xmsfb"></button>
<form id="xmsfb"><optgroup id="xmsfb"></optgroup></form><\/code> —simple and effective.<\/p>

9. Custom Utility Function (Mini jQuery Substitute)<\/strong><\/h3>

If you miss the convenience, write a lightweight wrapper:<\/p>

 const $ = (selector, context = document) => context.querySelector(selector);\nconst $$ = (selector, context = document) => [...context.querySelectorAll(selector)];\n\n\/\/ Usage:\nconst header = $('.header');\nconst links = $$('nav a');\n\n\/\/ Add methods\n$.on = (target, event, selector, handler) => {\n  target.addEventListener(event, (e) => {\n    if (e.target.matches(selector)) handler.call(e.target, e);\n  });\n};\n\n\/\/ Use it:\n$.on(document, 'click', '.btn', (e) => alert('Clicked!'));<\/pre>

This gives you jQuery-like syntax without the overhead.<\/p>


10. Performance Tips<\/strong><\/h3>
  • Cache selectors<\/strong> when used repeatedly.<\/li>
  • Use event delegation<\/strong> for dynamic or large lists.<\/li>
  • Avoid frequently DOM reads\/writes— batch changes<\/strong> when possible.<\/li>
  • Use DocumentFragment<\/strong> for inserting many elements:<\/li><\/ul>
     const fragment = document.createDocumentFragment();\nfor (let i = 0; i < 100; i ) {\n  const li = document.createElement('li');\n  li.textContent = `Item ${i}`;\n  fragment.appendChild(li);\n}\nlist.appendChild(fragment); \/\/ One reflow<\/pre>
    \n

    Basically, modern JavaScript gives you everything jQuery offered—and more—without the extra library. With querySelector<\/code> , classList<\/code> , addEventListener<\/code> , and insertAdjacentHTML<\/code> , you can do advanced DOM manipulation cleanly and efficiently.<\/p>\n

    It's not complex, but it's easy to overlook how far vanilla JS has come.<\/p>"}

    亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

    Table of Contents
    2. Event Delegation Without jQuery
    3. Creating and Inserting Elements
    4. Updating Attributes, Classes, and Styles
    Attributes
    Classes (with classList )
    Inline Styles
    5. Traversing the DOM
    6. Remove Elements
    7. Working with HTML and Text Content
    8. Waiting for DOM Ready (Without jQuery Ready)
    9. Custom Utility Function (Mini jQuery Substitute)
    10. Performance Tips
    Home Web Front-end JS Tutorial Advanced DOM Manipulation without jQuery

    Advanced DOM Manipulation without jQuery

    Jul 27, 2025 am 12:52 AM
    java programming

    Modern 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.

    Advanced DOM Manipulation without jQuery

    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.

    Advanced DOM Manipulation without jQuery

    1. Selecting Elements Like jQuery

    jQuery made element selection easy with its flexible $() syntax. Modern JavaScript offers equally expressive methods:

     // Single element (like $(&#39;selector&#39;).get(0) or $(&#39;selector&#39;)[0])
    const el = document.querySelector(&#39;.my-class&#39;);
    
    // Multiple elements (returns NodeList, like jQuery collection)
    const els = document.querySelectorAll(&#39;.my-items&#39;);
    
    // Match on data attributes, states, etc.
    const activeLinks = document.querySelectorAll(&#39;a.active[data-toggle]&#39;);

    ? Tip : Use Array.from() or spread syntax to convert NodeList to an array for map , filter , etc.:

    Advanced DOM Manipulation without jQuery
     const texts = [...document.querySelectorAll(&#39;li&#39;)].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(&#39;click&#39;, (e) => {
      // Check if the clicked element matches a selector
      if (e.target.matches(&#39;button.delete&#39;)) {
        console.log(&#39;Deleting item:&#39;, e.target.dataset.id);
      }
    });

    ? Works even for elements added later.
    ? Avoids memory leaks from orphaned event listeners.

    Advanced DOM Manipulation without jQuery

    3. Creating and Inserting Elements

    jQuery: $(&#39;<div class="box">Content</div>&#39;).appendTo(&#39;#container&#39;);

    Vanilla JS:

     const div = document.createElement(&#39;div&#39;);
    div.className = &#39;box&#39;;
    div.textContent = &#39;Content&#39;;
    
    document.getElementById(&#39;container&#39;).appendChild(div);

    Or use insertAdjacentHTML() for quick HTML injection:

     document.body.insertAdjacentHTML(&#39;beforeend&#39;, &#39;<div class="alert">New message</div>&#39;);

    ? Positions: &#39;beforebegin&#39; , &#39;afterbegin&#39; , &#39;beforeend&#39; , &#39;afterend&#39;


    4. Updating Attributes, Classes, and Styles

    Attributes

     el.setAttribute(&#39;data-id&#39;, 123);
    el.getAttribute(&#39;href&#39;);
    el.removeAttribute(&#39;disabled&#39;);

    Classes (with classList )

     el.classList.add(&#39;active&#39;);
    el.classList.remove(&#39;hidden&#39;);
    el.classList.toggle(&#39;visible&#39;);
    el.classList.contains(&#39;selected&#39;);

    Inline Styles

     el.style.opacity = &#39;0.5&#39;;
    el.style.display = &#39;none&#39;;
    
    // For multiple styles, consider using CSS classes instead
    el.classList.add(&#39;fade-out&#39;);

    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(&#39;.child&#39;) el.querySelector(&#39;.child&#39;) or el.querySelectorAll()

    Example:

     const parent = el.parentNode;
    const firstChild = parent.firstElementChild;
    const lastChild = parent.lastElementChild;

    6. Remove Elements

    jQuery: $(&#39;#item&#39;).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 = &#39;<b>new</b>&#39;
    Get text only el.textContent
    Set text only el.textContent = &#39;Plain text&#39;

    ?? 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(&#39;DOMContentLoaded&#39;, () => {
      console.log(&#39;DOM is ready&#39;);
    });

    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 = $(&#39;.header&#39;);
    const links = $$(&#39;nav a&#39;);
    
    // 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, &#39;click&#39;, &#39;.btn&#39;, (e) => alert(&#39;Clicked!&#39;));

    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(&#39;li&#39;);
      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!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

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

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Hot Topics

    PHP Tutorial
    1488
    72
    VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

    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

    How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

    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.

    Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

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

    python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

    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 for Data Engineering ETL Python for Data Engineering ETL Aug 02, 2025 am 08:48 AM

    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.

    python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

    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.

    Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

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

    How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

    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

    See all articles