简体   繁体   English

编写此DOM操作的更有效/适当的方法?

[英]More efficient/appropriate way to write this DOM manipulation?

I'm a beginner in Vanilla JavaScript and just made code to change HTML below. 我是Vanilla JavaScript的初学者,只是在下面创建了更改HTML的代码。 It works but I'd like to know if there is a more efficient/appropriate way of doing this. 它有效,但我想知道是否有更有效/适当的方法来做到这一点。 Thank you in advance for your help. 预先感谢您的帮助。

HTML BEFORE HTML 之前

<section id="anchor-a">
<p>lorem ipsum....</p>
</section>
<section id="anchor-b">
<p>lorem ipsum....</p>
</section>

HTML AFTER HTML AFTER

<section>
<div id="anchor-a" class="anchor"></div>
<p>lorem ipsum....</p>
</section>
<section>
<div id="anchor-b" class="anchor"></div>
<p>lorem ipsum....</p>
</section>

My JavaScript Code 我的JavaScript代码

const anchor = document.querySelectorAll('[id^="anchor-"]');
anchor.forEach((element) => {
  let newDiv = document.createElement('div');
  newDiv.classList.add('anchor');
  newDiv.setAttribute('id', element.getAttribute("id"));
  ;
  element.insertBefore(newDiv, element.firstChild);
  element.removeAttribute('id');
});

A more concise version would be to insertAdjacentHTML , which might be easier to read: 一个更简洁的版本是insertAdjacentHTML ,它可能更容易阅读:

 const anchor = document.querySelectorAll('[id^="anchor-"]'); anchor.forEach((section) => { section.insertAdjacentHTML('afterbegin', `<div id="${section.id}">`); section.removeAttribute('id'); }); // next line is not needed, just cleans up the console output for demonstration document.currentScript.remove(); console.log(document.body.innerHTML); 
 <section id="anchor-a"> <p>lorem ipsum....</p> </section> <section id="anchor-b"> <p>lorem ipsum....</p> </section> 

Also note that querySelectorAll returns a NodeList , and only newer browsers have a NodeList.prototype.forEach function. 另请注意, querySelectorAll返回NodeList ,只有较新的浏览器具有NodeList.prototype.forEach函数。 For older browsers and IE, either include a polyfill, or use Array.prototype.forEach.call instead: 对于旧版浏览器和IE,要么包含polyfill,要么使用Array.prototype.forEach.call

 Array.prototype.forEach.call( document.querySelectorAll('[id^="anchor-"]'), (section) => { section.insertAdjacentHTML('afterbegin', `<div id="${section.id}">`); section.removeAttribute('id'); } ); // next line is not needed, just cleans up the console output for demonstration document.currentScript.remove(); console.log(document.body.innerHTML); 
 <section id="anchor-a"> <p>lorem ipsum....</p> </section> <section id="anchor-b"> <p>lorem ipsum....</p> </section> 

(also, of course, if using ES6+ syntax, remember to transpile down to ES5 in addition to polyfills if you want to support ancient browsers) (当然,如果使用ES6 +语法,如果你想支持古老的浏览器,请记得除了polyfill之外还要转向ES5)

Focusing this answer on performance, manipulating DOM in a loop is a bad idea. 将这个答案集中在性能上,在循环中操作DOM是一个坏主意。 DOM interactions are the expensive operation, it is always advised to perform operation in loop. DOM交互是昂贵的操作,始终建议在循环中执行操作。

What I would suggest is: 我建议的是:

  • Locate the parent element where search is to be performed. 找到要执行搜索的父元素。
  • Make a clone of that. 克隆一下。
  • Perform your action on the elements. 对元素执行操作。 Since you are working on clone, you are not changing anything on DOM. 由于您正在使用clone,因此您不会更改DOM上的任何内容。 Any operation done is in memory only. 完成的任何操作仅在内存中。
  • Now remove this container element and add processed clone to the parent element. 现在删除此容器元素并将已处理的clone添加到父元素。

 var container = document.querySelector('.container'); var copy = container.cloneNode(true); const anchor = copy.querySelectorAll('[id^="anchor-"]'); anchor.forEach((element) => { let newDiv = document.createElement('div'); newDiv.classList.add('anchor'); newDiv.setAttribute('id', element.getAttribute("id"));; element.insertBefore(newDiv, element.firstChild); element.removeAttribute('id'); }); container.insertAdjacentElement('afterend', copy) container.remove(); 
 <div class='container'> <section id="anchor-a"> <p>lorem ipsum....</p> </section> <section id="anchor-b"> <p>lorem ipsum....</p> </section> </div> 

Note: not changing any code relation to element processing as CertainPerformance 's addresses that 注意:不改变任何与元素处理的代码关系,因为CertainPerformance的地址是

Interesting read: 有趣的读物:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM