The DOM-API method Element.getBoundingClientRect returns the bounds of an element. Unfortunately, this is not necessarily the bounds to which content is actually rendered. Given the following examples shows there is a discrepancy:
<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 text is rendered as follows (more or less):
First
XXXXX Second
Info
Clicking on Info shows the following message:
First x: 8; second x: 8
However, obviously the text content of the second paragraph is not rendered at the same x location as the text content of the first paragraph.
How can I determine the actual location of the (second) rendered text?
I found a workaround, which does not work in all cases by simply adding an empty span as first element to the paragraphs and retrieving the location of that span. But this does not work in all cases and the span may have some other side effects as well.
Context: I need that functionality for tests (using selenium webdriver). I also tried the webdriver's API function WebElement.getRect, but that returns the same result as getBoundingClientRect (which is used under the hood according to its documentation).
My question is not about fixing the layout, it is about retrieving the coordinates of the displayed text for testing purposes (e.g., for finding broken layouts).