Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does Element.getClientRects() return a collection of multiple objects?

Each time when I call Element.getClientRects(), it returns a collection of only one DOMRect object.

When does Element.getClientRects() return a collection of multiple DOMRect objects?

function handleClick() {
  console.log(event.target.getClientRects())
}
<ul 
  style="border: 1px solid black;" 
  onclick="handleClick()"
>
    <li>Click the text to see in console</li>
</ul>
like image 602
Roman Roman Avatar asked Dec 08 '18 17:12

Roman Roman


1 Answers

The return value of Element.getClientRects() method is a collection of DOMRect objects, each associated with one CSS border-box around an element.

When elements have multiple border-boxes (like inline-elements), then Element.getClientRects() returns multiple DOMRect objects. An example:

let p = document.querySelector('p');
let span = document.querySelector('span');

console.log(p.getClientRects().length);
console.log(span.getClientRects().length);
p {
  border: 1px solid green;
}
span {
  border: 1px solid red;
}
<p>
  This is a paragraph with
  <span>Span Element having a looooooooooooooooooooooo nnnnnnnnnnnnnnnnnnnn ggggggggggggggggg text</span>
</p>

Also, the return value is dependant on the screen resolution. Smaller the size, smaller will be the number of CSS border-boxes.

like image 191
vrintle Avatar answered Nov 09 '22 13:11

vrintle