# Insert a div into the specified html code to wrap it

**URL:** <https://meta.discourse.org/t/insert-a-div-into-the-specified-html-code-to-wrap-it/319942>\
**Category:** Development\
**Created:** [August 3, 2024, 6:34am UTC](https://meta.discourse.org/t/insert-a-div-into-the-specified-html-code-to-wrap-it/319942 "2024-08-03T06:34:55Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![Lhc\_fl](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/lhc_fl/32/268115_2.png) [@Lhc\_fl](https://meta.discourse.org/u/Lhc_fl)\
**Post date:** [August 3, 2024, 9:33am UTC](https://meta.discourse.org/t/insert-a-div-into-the-specified-html-code-to-wrap-it/319942/5 "2024-08-03T09:33:26Z")

</div>

![image](https://global.discourse-cdn.com/meta/original/4X/5/a/a/5aafbf1a0a8cc8744a5609d3a4f992a488b2f8a6.png)

I guess it works – Can you share how you use this code?

However, we also have element changes in the same page. Therefore, I made some modifications to your code, which should meet the requirements:

```javascript
const throttle = require("@ember/runloop").throttle;

const context = {
  wrapImg() {
    const avatarImages = document.querySelectorAll('img.avatar:not(.wrapped)');
    avatarImages.forEach(img => {
      // 创建一个新的 div 元素，并设置其类名为 by9700
      const wrapper = document.createElement('div');
      wrapper.className = 'by9700';
      // 将 img 元素移入到新的 div 中
      img.parentNode.insertBefore(wrapper, img);
      wrapper.appendChild(img);
      // 对 img 做标记
      img.classList.add("wrapped");
    });
  }
};

new MutationObserver(() => {
  throttle(context, context.wrapImg, 100);
}).observe(document.body, {
  childList: true, // 观察目标子节点的变化，是否有添加或者删除
  attributes: false, // 不观察属性变动
  subtree: true // 递归观察子节点
});

```

---

_[View the full topic](https://meta.discourse.org/t/insert-a-div-into-the-specified-html-code-to-wrap-it/319942)._
