简体   繁体   中英

ResizeObserver: How to retrieve the Id of the resized element?

I'm observing multiple textareas with ResizeObserver. The "for (let entry of entries)" loop enumerates all entries but I need only the id of the element that has been resized. I tried this.id but it's not defined.

var myObserver = new ResizeObserver(entries => {

console.log(this.id);
  for (let entry of entries) {
    // do something
  }
});

var boxes = document.querySelectorAll('textarea');
boxes.forEach(box => {
  myObserver.observe(box);
});

It is possible for multiple textareas to change/resize at the same time, and so using an array to keep track of each of the changes is needed. However, most of the time, only one element will resize. In this case, you can get the first element from your entries , and get its target.id value:

 const myObserver = new ResizeObserver(entries => { const [changed] = entries; console.log(changed.target.id); }); const boxes = document.querySelectorAll('textarea'); boxes.forEach(box => { myObserver.observe(box); });
 <textarea id="1">1</textarea> <textarea id="2">12</textarea> <textarea id="3">123</textarea>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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