最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Child elements in webcomponent - Stack Overflow

programmeradmin3浏览0评论

Suppose we have a custom element to use in this way:

<list-image>
    <img src="" /> 
     ...
</list-image>

Where list-image displays img tags in a slider layout.

If the user of component inserts an img tag with:

document.querySelector('list-image').insertAdjacentHTML('beforeend', '<img src="..." />');

...Is it possible for the component to know the new element img?

Suppose we have a custom element to use in this way:

<list-image>
    <img src="" /> 
     ...
</list-image>

Where list-image displays img tags in a slider layout.

If the user of component inserts an img tag with:

document.querySelector('list-image').insertAdjacentHTML('beforeend', '<img src="..." />');

...Is it possible for the component to know the new element img?

Share Improve this question edited Sep 20, 2023 at 18:50 Tony Rogers 73 bronze badges asked Mar 24, 2017 at 17:18 asvasv 3,7928 gold badges28 silver badges51 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 13

The solution is to use a MutationObserver on the <list-image> custom element itself.

In the connectedCallback() method, observe mutations on child elements:

customElements.define('list-image', class extends HTMLElement {
  connectedCallback() {
    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        //Detect <img> insertion
        if (mutation.addedNodes.length)
          console.info('Node added: ', mutation.addedNodes[0])
      })
    })

    observer.observe(this, { childList: true })
  }
})

function add() {
  document.querySelector('list-image')
          .insertAdjacentHTML('beforeend', '<img alt="TOTO" />')
}
<list-image>
  <img alt="Image1">
  <img alt="Image2">
</list-image>
<button onclick="add()">Add image</button>

Upadate, from this page: https://developers.google.com/web/fundamentals/web-components/examples/howto-tabs

New children will get slotted automatically and cause slotchange to fire, so not MutationObserver is needed.

发布评论

评论列表(0)

  1. 暂无评论