When using the DOM-API method Element.getBoundingClientRect, it may not always return the actual bounds where content is rendered. This can be seen in the following examples:
<html>
<head>
<style>
#float { float: left; }
</style>
<script>
function info() {
const boundFirst = document.getElementById('first').getBoundingClientRect();
const boundScnd = document.getElementById('scnd').getBoundingClientRect();
alert("First x: " + boundFirst.x + "; second x: " + boundScnd.x);
}
</script>
</head>
<body>
<p id="first">First</p>
<p id="float">XXXXX</p><p id="scnd">Second</p>
<p onclick="info()">Info</p>
</body>
</html>
The displayed text appears as follows:
First
XXXXX Second
Info
Clicking on Info reveals this message:
First x: 8; second x: 8
It's evident that the text content of the second paragraph is not rendered at the same x position as the first one.
How can I accurately determine the location of the rendered text?
A workaround involves adding an empty span before the paragraphs to retrieve its location, but this is not foolproof and may have unintended side effects.
For testing purposes (e.g., detecting broken layouts), I need a reliable way to obtain the coordinates of displayed text. The WebElement.getRect method in Selenium webdriver has yielded the same results as getBoundingClientRect under the hood.
This issue pertains to retrieving text coordinates for testing rather than fixing layout problems.