<table id="om8ii"></table>
  • <fieldset id="om8ii"><samp id="om8ii"></samp></fieldset>
    <option id="om8ii"></option>
  • <strike id="om8ii"></strike>
    <\/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 frequent 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国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

      目錄
      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. Removing 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
      首頁 web前端 js教程 沒有jQuery的高級DOM操縱

      沒有jQuery的高級DOM操縱

      Jul 27, 2025 am 12:52 AM
      java 編程

      現(xiàn)代JavaScript已取代jQuery,通過原生API即可高效操作DOM。1. 使用document.querySelector()和querySelectorAll()選擇元素,支持復雜選擇器;2. 利用事件委托,在父元素監(jiān)聽事件并用e.target.matches()判斷目標,提升動態(tài)內容性能;3. 通過document.createElement()創(chuàng)建元素,或用insertAdjacentHTML()插入HTML;4. 使用setAttribute()、classList和style屬性分別操作屬性、類名和樣式;5. 原生DOM遍歷如parentNode、nextElementSibling、querySelector等對應jQuery的遍歷方法;6. 調用el.remove()刪除元素,兼容舊瀏覽器可使用parentNode.removeChild();7. 用textContent獲取或設置文本內容,更安全高效,innerHTML用于插入HTML;8. 通過document.addEventListener('DOMContentLoaded')等待DOM加載完成;9. 可編寫$和$$函數(shù)模擬jQuery選擇器,并封裝$.on實現(xiàn)事件代理;10. 性能優(yōu)化建議包括緩存選擇器、使用事件委托、批量DOM操作及DocumentFragment減少重排。現(xiàn)代JavaScript憑借強大API已無需依賴jQuery,代碼更輕量、高效且易維護。

      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 maintainable. 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 $('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.:

      Advanced DOM Manipulation without jQuery
      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.

      Advanced DOM Manipulation without jQuery

      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 intuitive. Native equivalents:

      jQueryVanilla 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. Removing 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

      PurposeMethod
      Get inner HTMLel.innerHTML
      Set inner HTMLel.innerHTML = '<b>new</b>'
      Get text onlyel.textContent
      Set text onlyel.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 frequent 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.

      以上是沒有jQuery的高級DOM操縱的詳細內容。更多信息請關注PHP中文網其他相關文章!

      本站聲明
      本文內容由網友自發(fā)貢獻,版權歸原作者所有,本站不承擔相應法律責任。如您發(fā)現(xiàn)有涉嫌抄襲侵權的內容,請聯(lián)系admin@php.cn

      熱AI工具

      Undress AI Tool

      Undress AI Tool

      免費脫衣服圖片

      Undresser.AI Undress

      Undresser.AI Undress

      人工智能驅動的應用程序,用于創(chuàng)建逼真的裸體照片

      AI Clothes Remover

      AI Clothes Remover

      用于從照片中去除衣服的在線人工智能工具。

      Clothoff.io

      Clothoff.io

      AI脫衣機

      Video Face Swap

      Video Face Swap

      使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

      熱工具

      記事本++7.3.1

      記事本++7.3.1

      好用且免費的代碼編輯器

      SublimeText3漢化版

      SublimeText3漢化版

      中文版,非常好用

      禪工作室 13.0.1

      禪工作室 13.0.1

      功能強大的PHP集成開發(fā)環(huán)境

      Dreamweaver CS6

      Dreamweaver CS6

      視覺化網頁開發(fā)工具

      SublimeText3 Mac版

      SublimeText3 Mac版

      神級代碼編輯軟件(SublimeText3)

      熱門話題

      Laravel 教程
      1597
      29
      PHP教程
      1488
      72
      VSCODE設置。JSON位置 VSCODE設置。JSON位置 Aug 01, 2025 am 06:12 AM

      settings.json文件位于用戶級或工作區(qū)級路徑,用于自定義VSCode設置。1.用戶級路徑:Windows為C:\Users\\AppData\Roaming\Code\User\settings.json,macOS為/Users//Library/ApplicationSupport/Code/User/settings.json,Linux為/home//.config/Code/User/settings.json;2.工作區(qū)級路徑:項目根目錄下的.vscode/settings

      如何使用JDBC處理Java的交易? 如何使用JDBC處理Java的交易? Aug 02, 2025 pm 12:29 PM

      要正確處理JDBC事務,必須先關閉自動提交模式,再執(zhí)行多個操作,最后根據結果提交或回滾;1.調用conn.setAutoCommit(false)以開始事務;2.執(zhí)行多個SQL操作,如INSERT和UPDATE;3.若所有操作成功則調用conn.commit(),若發(fā)生異常則調用conn.rollback()確保數(shù)據一致性;同時應使用try-with-resources管理資源,妥善處理異常并關閉連接,避免連接泄漏;此外建議使用連接池、設置保存點實現(xiàn)部分回滾,并保持事務盡可能短以提升性能。

      在Java的掌握依賴注入春季和Guice 在Java的掌握依賴注入春季和Guice Aug 01, 2025 am 05:53 AM

      依賴性(di)IsadesignpatternwhereObjectsReceivedenciesenciesExtern上,推廣looseSecouplingAndEaseerTestingThroughConstructor,setter,orfieldInjection.2.springfraMefringframeWorkSannotationsLikeLikeLike@component@component,@component,@service,@autowiredwithjava-service和@autowiredwithjava-ligatiredwithjava-lase-lightike

      數(shù)據工程ETL的Python 數(shù)據工程ETL的Python Aug 02, 2025 am 08:48 AM

      Python是實現(xiàn)ETL流程的高效工具,1.數(shù)據抽取:通過pandas、sqlalchemy、requests等庫可從數(shù)據庫、API、文件等來源提取數(shù)據;2.數(shù)據轉換:使用pandas進行清洗、類型轉換、關聯(lián)、聚合等操作,確保數(shù)據質量并優(yōu)化性能;3.數(shù)據加載:利用pandas的to_sql方法或云平臺SDK將數(shù)據寫入目標系統(tǒng),注意寫入方式與批次處理;4.工具推薦:Airflow、Dagster、Prefect用于流程調度與管理,結合日志報警與虛擬環(huán)境提升穩(wěn)定性與可維護性。

      了解Java虛擬機(JVM)內部 了解Java虛擬機(JVM)內部 Aug 01, 2025 am 06:31 AM

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

      如何使用Java的日歷? 如何使用Java的日歷? Aug 02, 2025 am 02:38 AM

      使用java.time包中的類替代舊的Date和Calendar類;2.通過LocalDate、LocalDateTime和LocalTime獲取當前日期時間;3.使用of()方法創(chuàng)建特定日期時間;4.利用plus/minus方法不可變地增減時間;5.使用ZonedDateTime和ZoneId處理時區(qū);6.通過DateTimeFormatter格式化和解析日期字符串;7.必要時通過Instant與舊日期類型兼容;現(xiàn)代Java中日期處理應優(yōu)先使用java.timeAPI,它提供了清晰、不可變且線

      Google Chrome無法打開本地文件 Google Chrome無法打開本地文件 Aug 01, 2025 am 05:24 AM

      ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

      了解網絡端口和防火墻 了解網絡端口和防火墻 Aug 01, 2025 am 06:40 AM

      NetworkPortSandFireWallsworkTogetHertoEnableCommunication whereSeringSecurity.1.NetWorkPortSareVirtualendPointSnumbered0-655 35,with-Well-with-Newonportslike80(HTTP),443(https),22(SSH)和25(smtp)sindiessingspefificservices.2.portsoperateervertcp(可靠,c

      See all articles